動態(tài)修改cron表達(dá)式
@RestController
@Component
public class DynamicTask {
/**
* 線程池任務(wù)調(diào)度類膘滨,能夠開啟線程池進(jìn)行任務(wù)調(diào)度砸烦。
*/
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
/**
* 定時計劃ScheduledFuture
*/
private ScheduledFuture<?> future;
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
return new ThreadPoolTaskScheduler();
}
/**
* ThreadPoolTaskScheduler.schedule()方法會創(chuàng)建一個定時計劃ScheduledFuture,
* 在這個方法需要添加兩個參數(shù)灭必,Runnable(線程接口類) 和CronTrigger(定時任務(wù)觸發(fā)器)
*/
@RequestMapping("/startCron")
public String startCron() {
future = threadPoolTaskScheduler.schedule(new MyRunnable(), new CronTrigger("0/5 * * * * *"));
System.out.println("DynamicTask.startCron()");
return "startCron";
}
/**
* 在ScheduledFuture中有一個cancel可以停止定時任務(wù)。
* 參數(shù)為true便可以停止
* @return
*/
@RequestMapping("/stopCron")
public String stopCron() {
if (future != null) {
future.cancel(true);
}
System.out.println("DynamicTask.stopCron()");
return "stopCron";
}
@RequestMapping("/changeCron10")
public String startCron10() {
stopCron();// 先停止炫惩,在開啟.
future = threadPoolTaskScheduler.schedule(new MyRunnable(), new CronTrigger("*/10 * * * * *"));
System.out.println("DynamicTask.startCron10()");
return "changeCron10";
}
private class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("DynamicTask.MyRunnable.run()," + new Date());
}
}
}
通過數(shù)據(jù)庫修改表達(dá)式
-
在數(shù)據(jù)庫中建一張表cron
屬性:cron_id,cron
-
建立一個和表對應(yīng)的持久化類
@Data
@Entity
public class Cron {
@GeneratedValue
@Id
private Integer cronId;
private String cron;
public Cron() {
}
public Cron(String cron) {
this.cron = cron;
}
}
-
寫一個CronRepository接口
public interface CronRepository extends JpaRepository<Cron,Integer>{
}
-
實現(xiàn)
@Configuration
@EnableScheduling
public class CompleteScheduleConfig implements SchedulingConfigurer {
// 0/5 * * * * *
// */10 * * * * *
@Resource
private CronRepository cronRepository;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.addTriggerTask(
//1.添加任務(wù)內(nèi)容(Runnable)
() -> System.out.println("執(zhí)行定時任務(wù)2: " + LocalDateTime.now().toLocalTime()),
//2.設(shè)置執(zhí)行周期(Trigger)
triggerContext -> {
//2.1 從數(shù)據(jù)庫獲取執(zhí)行周期
String cron = cronRepository.findById(23).get().getCron();
//2.2 合法性校驗.
if (StringUtils.isEmpty(cron)) {
// Omitted Code ..
}
//2.3 返回執(zhí)行周期(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
);
}
}