判断cron表达式是否在当前时间(或者指定时间)执行

1.判断cron 表达式是否在当前时间执行
例如: cron(0 0 0 * * ? *) 是否在今天执行

public static boolean getLastRunTimeByCron(String cron) {
        List<Date> dates = null;
        try {
            CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
            cronTriggerImpl.setCronExpression(cron);
            dates = TriggerUtils.computeFireTimes(cronTriggerImpl, null, 1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (dates != null && dates.size() != 0) {
            Date date = dates.get(0);
            //传入时间
            //LocalDate dDate = localDate;
            long epochMilli = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
            Date firstDate = new Date(epochMilli);
            Date lastDate = new Date(epochMilli+86400000);
            if (date.before(lastDate) && date.after(firstDate)) {
                return true;
            }else if (date.compareTo(firstDate) == 0 || date.compareTo(lastDate) == 0) {
                return true;
            }else {
                return false;
            }
        }else {
            return false;
        }
    }

2、注意

参数可传入时间,判断cron是否在特定时间执行
//传入时间
 LocalDate dDate = localDate;
 long epochMilli = LocalDateTime.of(*dDate*, LocalTime.MIN).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();

3、cron表达式翻译

//通过Cron翻译
    public String getByCron(String cron) {
        String cronExplain = null;
        if (StringUtils.isNotEmpty(CronExpParser.translateToChinese(cron))){
            cronExplain = CronExpParser.translateToChinese(cron);
        }
        return cronExplain;
    }

引入工具类 CronExpParser

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值