今天遇到这样的问题,开发一个定时任务,在本地开发模拟正式环境,则需要傻傻的调整系统时间,触发定时任务。╮(╯▽╰)╭
网上查询发现了一种解决方案:
需要使用quartz的jar包中提供的TriggerUtils类来计算
package test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.quartz.TriggerUtils;
import org.quartz.impl.triggers.CronTriggerImpl;
public class CronTest {
/**
* @param args
* @throws ParseException
* @throws InterruptedException
*/
public static void main(String[] args) throws ParseException, InterruptedException {
CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
cronTriggerImpl.setCronExpression("0 41 7-22 * * ?");//这里写要准备猜测的cron表达式
Calendar calendar = Calendar.getInstance();
Date now = calendar.getTime();
calendar.add(Calendar.YEAR, 2);//把统计的区间段设置为从现在到2年后的今天(主要是为了方法通用考虑,如那些1个月跑一次的任务,如果时间段设置的较短就不足20条)
List<Date> dates = TriggerUtils.computeFireTimesBetween(cronTriggerImpl, null, now, calendar.getTime());//这个是重点,一行代码搞定~~
System.out.println(dates.size());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for(int i =0;i < dates.size();i ++){
if(i >29){//这个是提示的日期个数
break;
}
System.out.println(dateFormat.format(dates.get(i)));
}
}
}