用 ScheduledThreadPoolExecutor 实现netty中的定时任务

浪子不回头ぞ 提交于 2020-08-14 22:47:56

代码结构:

.
|____Main.java
|____ScheduledThreadPoolExecutorMgr.java
 


 


|____Main.java

package scheduledthreadpoolexecutortest;

import java.util.concurrent.RunnableScheduledFuture;

public class Main {

    public static int count = 0;

    public static RunnableScheduledFuture runnable;

    public static void main(String[] args) {
        long start = System.currentTimeMillis();

        runnable = ScheduledThreadPoolExecutorMgr.schedule(new Runnable() {
            @Override
            public void run() {
                count++;
                System.out.println("第" + count + "次运行" + " " + Thread.currentThread().getName() + " 在 " + (System.currentTimeMillis() - start) + " ms后");
            }
        }, 0, 1);

        ScheduledThreadPoolExecutorMgr.scheduleOnce(new Runnable() {
            @Override
            public void run() {
                System.out.println("cancel");
                ScheduledThreadPoolExecutorMgr.cancel(runnable);
            }
        }, 3);

    }
}

/*
第1次运行 pool-1-thread-1 在 9 ms后
第2次运行 pool-1-thread-2 在 1010 ms后
第3次运行 pool-1-thread-3 在 2011 ms后
第4次运行 pool-1-thread-1 在 3011 ms后
cancel
 */


|____ScheduledThreadPoolExecutorMgr.java

package scheduledthreadpoolexecutortest;

import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPoolExecutorMgr {
    // 任务线程池
    private static ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors());

    /**
     * 定时任务
     *
     * @param runnable         执行的任务
     * @param initDelayTimeSec 初始延迟多久
     * @param everyTimeSec     每次间隔多久
     * @return
     */
    public static RunnableScheduledFuture schedule(Runnable runnable, int initDelayTimeSec, int everyTimeSec) {
        ScheduledFuture<?> scheduledFuture = scheduled.scheduleAtFixedRate(runnable, initDelayTimeSec, everyTimeSec, TimeUnit.SECONDS);
        return (RunnableScheduledFuture) scheduledFuture;
    }

    /**
     * 只执行一次的任务
     *
     * @param runnable         执行的任务
     * @param initDelayTimeSec 延迟多少秒开始执行
     * @return
     */
    public static RunnableScheduledFuture scheduleOnce(Runnable runnable, int initDelayTimeSec) {
        ScheduledFuture<?> schedule = scheduled.schedule(runnable, initDelayTimeSec, TimeUnit.SECONDS);
        return (RunnableScheduledFuture) schedule;
    }

    /**
     * 取消一个任务
     */
    public static void cancel(RunnableScheduledFuture runnable) {
        scheduled.remove(runnable);
    }

    /**
     * 关闭定时任务
     */
    public static void shutdown() {
        scheduled.shutdown();
    }
}


 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!