手动关闭Spring定时任务

一、问题

比如我写了一个这样的定时任务类,该定时任务很简单:每秒打印一行craneing…
手动关闭Spring定时任务_第1张图片
那么后期我想中途关闭和开启这个定时任务应该怎么处理?

二、解决

spring定时任务依赖 ThreadPoolTaskScheduler 这个类,我们只需要顶掉这个自动装配的bean,自己写一些逻辑就行了
手动关闭Spring定时任务_第2张图片

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 * * * * *"));
    }
 
}

你可能感兴趣的:(springboot,spring,java,后端)