Spring提供了CronSequenceGenerator类以便计算cron表达式的具体时间点的next方法(Spring3.2版本)和cron是否合法的isValidExpression方法(Spring4.3版本)。
实战举例:
package construct;
import org.springframework.scheduling.support.CronSequenceGenerator;
import java.util.Date;
/**
* Created by zhangzh on 2017/1/18.
*/
public class CronSequenceGeneratorTest {
public static void main(String[] args) {
String cron = "0 */5 * * * ?"; //每个五分钟执行一次
CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cron);
Date currentTime = new Date();
System.out.println("currentTime: " + currentTime);
Date nextTimePoint = cronSequenceGenerator.next(currentTime); // currentTime为计算下次时间点的开始时间
System.out.println("nextTimePoint: " + nextTimePoint);
Date nextNextTimePoint = cronSequenceGenerator.next(nextTimePoint);
System.out.println("nextNextTimePoint: " + nextNextTimePoint);
}
}
currentTime: Wed Jan 18 19:45:25 CST 2017
nextTimePoint: Wed Jan 18 19:50:00 CST 2017
nextNextTimePoint: Wed Jan 18 19:55:00 CST 2017
看,简单吧!