“This article has participated in the weekend learning plan, click to see details”

One, foreword

Timers come in three forms:

  • It is executed periodically at a fixed period
  • The execution is delayed for a certain period of time
  • Specify a time to execute

JDKThree commonly used timer implementation modes are provided as follows:

  • Timer
  • DelayedQueueDelays in the queue
  • ScheduledThreadPoolExecutor





(1)Timer

It is found that eureka uses a large number of timers:

  • TimerBelong toJDKCompared to earlier versions of the implementation, it can implement fixed-cycle tasks, as well as deferred tasks.
  • TimerAn asynchronous thread is started to execute the due task, which can be scheduled for execution only once or can be periodically repeated multiple times.

Example code for how Timer is used is as follows:

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run(a) {
        // Business code}},5000.5000);  // After 5s, a scheduled task is scheduled in 5s
Copy the code
  • TimerTaskIs to implement theRunnableThe abstract class of the interface
  • TimerResponsible for scheduling and executionTimerTask

The internal structure of Timer is as follows:

public class Timer {
    // Run O(1), add O(logn), cancel O(logn)
    private final TaskQueue queue = new TaskQueue();
    // Create another thread, task processing, will poll queue
    private final TimerThread thread = new TimerThread(queue);
    public Timer(String name) { thread.setName(name); thread.start(); }}Copy the code

TimerIt has a number of design flaws, so it is not recommended:

  • TimerIt’s single-threaded mode, if someTimerTaskThe execution takes a long time, which affects the scheduling of other tasks.
  • TimerTask scheduling is based on the absolute system time. If the system time is incorrect, problems may occur.
  • TimerTaskIf the execution is abnormal,TimerNo capture is done, the thread terminates, and other tasks are never executed.





(2)DelayedQueueDelays in the queue

Features are as follows:

  • DelayedQueueJDKA blocking queue that can delay the acquisition of objects, internally using a priority queuePriorityQueueStore the object
  • DelayQueueEach object in must be implementedDelayedInterface, rewritecompareTogetDelaymethods

DelayedQueue can be used as follows:

public class DelayQueueTest {
    public static void main(String[] args) throws Exception {
        BlockingQueue<SampleTask> delayQueue = new DelayQueue<>();
        long now = System.currentTimeMillis();
        delayQueue.put(new SampleTask(now + 1000));
        delayQueue.put(new SampleTask(now + 2000));
        delayQueue.put(new SampleTask(now + 3000));
        for (int i = 0; i < 3; i++) {
            System.out.println(newDate(delayQueue.take().getTime())); }}static class SampleTask implements Delayed {
        long time;
        public SampleTask(long time) {
            this.time = time;
        }
        public long getTime(a) {
            return time;
        }
        @Override
        public int compareTo(Delayed o) {
            return Long.compare(this.getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS));
        }
        @Override
        public long getDelay(TimeUnit unit) {
            returnunit.convert(time - System.currentTimeMillis(), TimeUnit.MILLISECONDS); }}}Copy the code





(3)ScheduledThreadPoolExecutor

The JDK ScheduledThreadPoolExecutor provides function more rich

public class ScheduledExecutorServiceTest {
    public static void main(String[] args) {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
        executor.scheduleAtFixedRate(() -> System.out.println("Hello World"), 1000.2000, TimeUnit.MILLISECONDS); // The task is executed after 1s delay. The task is repeated every 2s}}Copy the code

ScheduledThreadPoolExecutor USES the blocking queue DelayedWorkQueue.