使用ScheduledExecutorService线程池创建定时任务

@RestController
@RequestMapping("/schedule")
public class ScheduledController {

    public static Map<String,Boolean> taskInfo = new HashMap<>(4);

    @PostConstruct
    public void init(){
        taskInfo.put("at",true);
        taskInfo.put("with",true);
    }

    @GetMapping("/stop/task/{taskName}")
    public String stopTask(@PathVariable String taskName){
        taskInfo.put(taskName,false);
        return "ok";
    }

    @GetMapping("/execute/at/{initialDelay}")
    public String executeAt(@PathVariable Integer initialDelay){
        taskInfo.put("at",true);
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        //以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕,如果上一个任务执行完毕,则当前任务立即执行,如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行。
        executorService.scheduleAtFixedRate(()->{
            if(!taskInfo.get("at")){
                throw new RuntimeException("任务停止-----------");
            }
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " " + TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
        },initialDelay,2, TimeUnit.SECONDS);
        return "ok";
    }

    @GetMapping("/execute/with/{initialDelay}")
    public String executeWith(@PathVariable Integer initialDelay){
        taskInfo.put("with",true);
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        //以上一个任务结束时开始计时,period时间过去后,立即执行
        executorService.scheduleWithFixedDelay(()->{
            if(!taskInfo.get("with")){
                throw new RuntimeException("任务停止-----------");
            }
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
        },initialDelay,2, TimeUnit.SECONDS);
        return "ok";
    }
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×