定时任务帮助类
package com.xcg.webapp.common;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**final类不可以继承*/
public final class ScheduledThreadUtil {
    /**静态代码块*/
    static {

    }

    /**
     * 不可以创建新对象
     */
    private ScheduledThreadUtil() {
    }

    /**
     * 存储定时任务
     * */
    private static Map<String, ScheduledFuture> scheduledFutureMap = new HashMap<>();
    /**
     * 可调度线程池
     * */
    private static ScheduledThreadPoolExecutor threadPoolExecutor = null;
    /**
     * 保持线程池单实例
     * */
    public static ScheduledThreadPoolExecutor getThreadPoolExecutorInstance() {
        if (threadPoolExecutor == null) {
            synchronized (ScheduledThreadUtil.class) {
                if (threadPoolExecutor == null) {
                    threadPoolExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(16);
                }
            }
        }
        return threadPoolExecutor;
    }

    /**
     * 执行定时任务
     */
    public static void doJob(String key, Runnable job, int initialDelay, int period) {
        //避免重复的任务
        if (!scheduledFutureMap.containsKey(key)) {
            getThreadPoolExecutorInstance();
            // 参数1: task任务;
            // 参数2: 首次执行任务的延迟时间;
            // 参数3: 周期性执行的时间;
            // 参数4: 时间单位;
            var task = threadPoolExecutor.scheduleAtFixedRate(job, initialDelay, period, TimeUnit.SECONDS);
            scheduledFutureMap.put(key, task);
        }
    }

    /**
     * 停止定时任务(非强制,如果正在执行,会等待执行完成后再关闭。)
     */
    public static void removeJob(String key) {
        if (scheduledFutureMap.containsKey(key)) {
            var task = scheduledFutureMap.get(key);
            task.cancel(false);
        }
    }

    /**
     * 停止全部任务(非强制,如果正在执行,会等待执行完成后再关闭。)
     */
    public static void removeAllJob() {
        if (threadPoolExecutor != null) {
            threadPoolExecutor.shutdown();
        }
    }
}

 测试

        //设置定时任务
        ScheduledThreadUtil.doJob("job1", new Runnable() {
            @Override
            public void run() {
                System.out.println("定时任务1,每1秒执行一次:" + DateUtil.format(new Date(), DateUtil.DF_YYYY_MM_DDHHMMSS));
            }
        }, 1, 1);

        ScheduledThreadUtil.doJob("job2", new Runnable() {
            @Override
            public void run() {
                System.out.println("定时任务2,每5秒执行一次:" + DateUtil.format(new Date(), DateUtil.DF_YYYY_MM_DDHHMMSS));
            }
        }, 1, 5);

        Thread.sleep(20000);
        ScheduledThreadUtil.removeJob("job1");
        Thread.sleep(20000);
        ScheduledThreadUtil.removeAllJob();

 

posted on 2023-08-10 09:24  邢帅杰  阅读(31)  评论(0编辑  收藏  举报