SpringBoot 动态修改定时任务频率

2020-05-13 14:20:53 浏览数 (1)

本文共636字 阅读约需1分钟

代码语言:javascript复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;


@RestController
@RequestMapping(value = "test")
public class TestController {

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    private ScheduledFuture<?> future;

    // 线程池任务调度类
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    private String cronStr = "0/5 * * * * *";

    @RequestMapping("/start")
    public String startCron() {
        // 创建定时计划
        future = threadPoolTaskScheduler.schedule(new MyRunnable(), new Trigger(){
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext){
                return new CronTrigger(cronStr).nextExecutionTime(triggerContext);
            }
        });
        System.out.println("DynamicTask.startCron()");
        return "startCron";
    }

    @RequestMapping("/stop")
    public String stopCron() {

        if (future != null) {
            future.cancel(true);
        }
        System.out.println("DynamicTask.stopCron()");
        return "stopCron";
    }

    @PostMapping("/change")
    public String changeCron(@RequestBody String cron) {
        cronStr = cron;
        // 先停止,在开启
        stopCron();
        future = threadPoolTaskScheduler.schedule(new MyRunnable(), new Trigger(){
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext){
                return new CronTrigger(cronStr).nextExecutionTime(triggerContext);
            }
        });
        System.out.println("DynamicTask.changeCron()");
        return "changeCron";
    }

    private class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("DynamicTask.MyRunnable.run(),"   new Date());
        }
    }
}

调试情况如下: 1.调用start 2.调用change,并传入0/3 * * * * * 3.调用stop

0 人点赞