bingmous

欢迎交流,不吝赐教~

导航

ThreadPoolTaskScheduler实现定时任务

 

public class SchedulingTask {
    private static ThreadPoolTaskScheduler threadPoolTaskScheduler;
    static {
        threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setThreadNamePrefix("MySchedulingTask-");
        threadPoolTaskScheduler.setPoolSize(5);
        threadPoolTaskScheduler.initialize();
    }

    private Runnable task;

    private ScheduledFuture<?> future;

    private String cronStr = "";

    //定时任务
    public SchedulingTask() {}
    public SchedulingTask(Runnable task) {
        this.task = task;
    }
    public SchedulingTask(Runnable task, String cronStr) {
        this.task = task;
        this.cronStr = cronStr;
    }

    //启动定时任务
    public ScheduledFuture<?> startCron() {
        future = threadPoolTaskScheduler.schedule(task, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                return new CronTrigger(cronStr).nextExecutionTime(triggerContext);
            }
        });
        return future;
    }

    //取消定时任务
    public void stopCron() {
        if (future != null) {
            future.cancel(true);
        }
    }

    //修改定时任务
    public void changeCron(String cronStr) {
        this.cronStr = cronStr;
        stopCron();
        startCron();
    }

    //getter setter
    public Runnable getTask() {
        return task;
    }

    public ScheduledFuture<?> getFuture() {
        return future;
    }

    public String getCronStr() {
        return cronStr;
    }

    public void setTask(Runnable task) {
        this.task = task;
    }

    public void setCronStr(String cronStr) {
        this.cronStr = cronStr;
    }

    public static void setThreadPoolTaskScheduler(ThreadPoolTaskScheduler threadPoolTaskScheduler) {
        SchedulingTask.threadPoolTaskScheduler = threadPoolTaskScheduler;
    }


    //测试
//    public class MyTask implements Runnable {
//
//        @Override
//        public void run() {
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
//            System.out.println("running at " + format.format(new Date()));
//        }
//    }
}

cancel取消任务会发送中断信号到正在执行的线程,线程中可以使用Thread.interrupted()获取中断信号,线程中的Thread.sleep()会捕捉该中断异常。如果没有获取中断信号,线程会继续执行到结束

 

posted on 2021-10-17 21:13  Bingmous  阅读(541)  评论(0编辑  收藏  举报