參考文檔:html
https://www.jianshu.com/p/d160f2536de7ide
https://www.cnblogs.com/je-ge/p/6129667.htmlthis
核心方法就是下面這段代碼,經過實現SchedulingConfigurer接口來自定義cron的配置信息。在控制器中設定cron變量來達到控制定時任務。.net
@Component
public class DynamicScheduledTask implements SchedulingConfigurer {htm
// 設定一個默認值
private String cron = "0/10 * * * * ?";blog
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(
// 1.添加任務內容(Runnable)
() -> System.out.println("執行定時任務2: "),
// 2.設置執行週期(Trigger)
triggerContext -> {
// 2.3 返回執行週期(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
});
}接口
public void setCron(String cron) {
this.cron = cron;
}
}文檔
須要在Application類上添加註解信息:@EnableSchedulingget