工具类:使用延迟队列DelayQueue实现定时调度

JDK自身的定时调度(ScheduledExecutorService)已很完备,以下demo只是自己想熟悉 DelayQueue 而实现。

实现的功能点:

  1. 定时调度任务:周期执行、延迟执行
  2. 取消调度任务(实现类型Future的Cancel功能)
  3. 销毁整个调度服务

工具类 DelayQueueTimer

以下代码仅供测试:

package com.wj.util.delayQueueTimer;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

public class DelayQueueTimer {

    private volatile boolean isShutDown;

    private Thread thread;
    private DelayQueue<Task> queue = new DelayQueue<>();
    private Runnable runnable = () -> {
        try {
            while (!isShutDown) {
                Task task = queue.take();
                if (task.loop()) {
                    queue.add(task);
                }
                try {
                    task.task.run();
                } catch (Exception e) {
                    /* 任务线程抛出异常. */
                }
            }
        } catch (InterruptedException e) {
            /* 线程被终止.*/
        }
    };

    public DelayQueueTimer() {
        thread = new Thread(runnable);
        thread.start();
    }

    public DelayQueueTimer(ExecutorService executor) {
        executor.execute(runnable);
    }

    public void schedule(Runnable task, int delay) {
        queue.add(new Task(task, delay, TimeUnit.MILLISECONDS));
    }

    public void schedule(Runnable task, int delay, TimeUnit unit) {
        queue.add(new Task(task, delay, unit));
    }

    public void schedule(Runnable task, int delay, int period) {
        queue.add(new Task(task, delay, TimeUnit.MILLISECONDS, period));
    }

    public void schedule(Runnable task, int delay, TimeUnit unit, int period) {
        queue.add(new Task(task, delay, unit, period));
    }

    public void destory() {
        isShutDown = true;
        queue = null;
        if (thread != null) {
            thread.interrupt();
            thread = null;
        }
    }

    public void cancel(Runnable task) {
        queue.removeIf(t -> t.task == task);
    }

    public class Task implements Delayed {
        private Runnable task;
        private long triger;
        private long period;

        public Task(Runnable task, long delay, TimeUnit unit) {
            this(task, delay, unit, 0);
        }

        public Task(Runnable task, long delay, TimeUnit unit, long period) {
            this.task = task;
            this.triger = calculateNextTriger(delay, unit);
            this.period = unit.toNanos(period);
        }

        private long calculateNextTriger(long delay, TimeUnit unit) {
            return System.nanoTime() + unit.toNanos(delay);
        }

        public boolean loop() {
            if (period != 0) {
                this.triger = calculateNextTriger(period, TimeUnit.NANOSECONDS);
                return true;
            }
            return false;
        }

        @Override
        public int compareTo(Delayed delayed) {
            Task another = (Task) delayed;
            return Long.compare(this.triger, another.triger);
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(triger - System.nanoTime(), TimeUnit.NANOSECONDS);
        }
    }
}

测试类 Test

package com.wj.util.delayQueueTimer;

import java.util.concurrent.TimeUnit;

/**
 * 测试 DelayQueueTimer 工具类
 */
public class Test {

    public static void main(String[] args) throws InterruptedException {
        DelayQueueTimer timer = new DelayQueueTimer();

        /* 测试立即执行任务(默认毫秒). */
        Runnable task1 = () -> System.out.println("立即执行...");

        /* 测试延迟一秒执行任务,不循环执行(默认毫秒). */
        Runnable task2 = () -> System.out.println("延迟一秒执行");

        /* 测立即执行任务,每隔一秒循环执行(默认毫秒). */
        Runnable task3 = () -> System.out.println("立即开始执行,每隔一秒执行");

        /* 测试延迟2秒执行任务,每隔两秒执行(指定单位为秒). */
        Runnable task4 = () -> System.out.println("延迟2秒,每隔两秒执行");

        timer.schedule(task1, 0);
        timer.schedule(task2, 1000);
//        timer.schedule(task3, 0, 1000);
        timer.schedule(task4, 2, TimeUnit.SECONDS, 2);

        Thread.sleep(9000);

        timer.cancel(task4);
        System.err.println("task4 任务取消...");
        Thread.sleep(10000);

        timer.destory();
    }

}

测试结果:
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值