动态添加定时任务:
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {
private ScheduledTaskRegistrar taskRegistrar;
private Map<String, ScheduledFuture<?>> taskFutures = new ConcurrentHashMap<String, ScheduledFuture<?>>();
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
this.taskRegistrar = taskRegistrar;
}
public void addTriggerTask(String taskId, TriggerTask triggerTask){
if (taskFutures.containsKey(taskId)) {
throw new SchedulingException("the taskId[" + taskId + "] was added.");
}
TaskScheduler taskScheduler = taskRegistrar.getScheduler();
ScheduledFuture<?> future = taskScheduler.schedule(triggerTask.getRunnable(), triggerTask.getTrigger());
taskFutures.put(taskId, future);
}
}
调用:
new Thread(()->{scheduleConfig.addTriggerTask( taskId
,new TriggerTask(()->{
//问题: 请问此线程中如何取到 taskId的值??????
},new CronTrigger("/5 * * * ?")));}).start();