java 获取一天内crontab任务执行的时间点

时间:2022-07-23
本文章向大家介绍java 获取一天内crontab任务执行的时间点,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

获取当天crontab任务执行的时间点 网上有如下方法来获取执行时间点

List<Date> dates = TriggerUtils.computeFireTimesBetween(cronTriggerImpl, null, from, to);

但是,貌似这个方法已经过时无法使用了。 可以通过下面的方法,获取当天一整天内任务执行的时间点。

import org.quartz.CronExpression;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * Created by LiChao on 2018/6/1
 */
public class QuartzTest {

    public static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
    public static SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");

    public static void main(String[] args) throws ParseException {
        Date nextTime = df.parse(df2.format(new Date()) + " 00:00:00");
        Date to = new Date(nextTime.getTime() + 24*3600*1000);
        CronExpression expression;
        List<Date> crontimes = new ArrayList<>();
        expression = new CronExpression("0 0/30 9-17 * * ?");
        for(;nextTime.getTime()<=to.getTime();){
            nextTime = expression.getNextValidTimeAfter(nextTime);
            if(nextTime.getTime()>=to.getTime()) break;
            crontimes.add(nextTime);
        }
        for(int i=0;i<crontimes.size();i++){
            System.out.println(df.format(crontimes.get(i)));
        }
    }

}

输出如下:

2018-06-01 09:00:00
2018-06-01 09:30:00
2018-06-01 10:00:00
2018-06-01 10:30:00
2018-06-01 11:00:00
2018-06-01 11:30:00
2018-06-01 12:00:00
2018-06-01 12:30:00
2018-06-01 13:00:00
2018-06-01 13:30:00
2018-06-01 14:00:00
2018-06-01 14:30:00
2018-06-01 15:00:00
2018-06-01 15:30:00
2018-06-01 16:00:00
2018-06-01 16:30:00
2018-06-01 17:00:00
2018-06-01 17:30:00

Process finished with exit code 0

引入依赖包

<dependency>
      <groupId>opensymphony</groupId>
      <artifactId>quartz-all</artifactId>
      <version>1.6.3</version>
</dependency>