Junit 判断cron语句的正确性和下一次执行时间,Spring有提供类CronSequenceGenerator供我们使用
/**
* 判断cron语句的正确性
*/
@org.junit.Test
public void test4(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String cron = "0 */5 * * * ?"; //每个五分钟执行一次
if(CronSequenceGenerator.isValidExpression(cron)) {
System.out.println("表达式正确");
CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cron);
Date currentTime = new Date();
System.out.println("currentTime: " + sdf.format(currentTime));
Date nextTimePoint = cronSequenceGenerator.next(currentTime); // currentTime为计算下次时间点的开始时间
System.out.println("nextTimePoint: " + sdf.format(nextTimePoint));
Date nextNextTimePoint = cronSequenceGenerator.next(nextTimePoint);
System.out.println("nextNextTimePoint: " + sdf.format(nextNextTimePoint));
}else {
System.out.println("表达式错误");
}
}
测试结果:
表达式正确
currentTime: 2019-06-14 09:03:55
nextTimePoint: 2019-06-14 09:05:00
nextNextTimePoint: 2019-06-14 09:10:00
功能OK!