一、问题
比如我写了一个这样的定时任务类,该定时任务很简单:每秒打印一行craneing…
那么后期我想中途关闭和开启这个定时任务应该怎么处理?
二、解决
spring定时任务依赖 ThreadPoolTaskScheduler 这个类,我们只需要顶掉这个自动装配的bean,自己写一些逻辑就行了
2.1给容器添加自己写的ThreadPoolTaskScheduler,主要是用map来维护任务列表
@Component
public class CustomTaskScheduler extends ThreadPoolTaskScheduler {
private Map<Object, ScheduledFuture<?>> scheduledTasks = new IdentityHashMap<>();
@Override
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
ScheduledFuture<?> future = super.schedule(task, trigger);
this.putScheduledTasks(task, future);
return future;
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
ScheduledFuture<?> future = super.scheduleAtFixedRate(task, period);
this.putScheduledTasks(task, future);
return future;
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
ScheduledFuture<?> future = super.scheduleAtFixedRate(task, startTime, period);
this.putScheduledTasks(task, future);
return future;
}
private void putScheduledTasks(Runnable task, ScheduledFuture<?> future) {
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task;
scheduledTasks.put(runnable.getTarget(), future);
}
public Map<Object, ScheduledFuture<?>> getScheduledTasks() {
return scheduledTasks;
}
}
2.2controller手动控制案例
@RestController
@RequestMapping("task")
public class TaskSwitch{
@Autowired
private CustomTaskScheduler customTaskScheduler;
@Autowired
private TaskBean taskBean;
@RequestMapping("close")
public void close(){
customTaskScheduler.getScheduledTasks().get(taskBean).cancel(true);
}
@RequestMapping("open")
public void open(){
ScheduledMethodRunnable runnable = new ScheduledMethodRunnable(taskBean, ReflectionUtils.findMethod(taskBean.getClass(), "crane"));
customTaskScheduler.schedule(runnable, new CronTrigger("*/1 * * * * *"));
}
}