1 Application Scenario

  • Close idle connections. In the server, there are many client connections that need to be closed after a period of idle time.
  • Clearing expired data. For example, objects in the cache need to be removed from the cache when their idle time has expired.
  • The task timed out. In the network protocol sliding window request reply interaction, processing timeout unresponded requests.
  • The order will be automatically cancelled if payment is not made within 30 minutes of placing the order.
  • Meal order notification: An SMS notification will be sent to the user 60 seconds after the order is placed.
  • When the order has not been paid, how to close the order in time and return the inventory?
  • How to regularly check whether the order in refund status has been successfully refunded?
  • If a newly created store does not upload goods within N days, how can the system know this information and send an activation message?
  • Scheduled task scheduling: The DelayQueue is used to store the tasks that will be executed on the current day and the execution time. Once the tasks are obtained from the DelayQueue, the tasks will be executed.

2 delay task – implementation

  • Regular polling (database, etc.)
  • DelayQueue
  • Timer
  • ScheduledExecutorService
  • Time round (kafka)
  • RabbitMQ
  • Quartz
  • Redis Zset
  • Koala
  • JCronTab
  • SchedulerX
  • There is a like delay queue

2.1 the polling

Features: regular rotation training database, set state.

Advantages: Simple implementation Disadvantages: A large amount of data consumes too many I/O resources, resulting in low efficiencyCopy the code

2.2 DelayQueue

Features: unbounded, delayed, blocking queues

A, BlockingQueue+PriorityQueue +Delayed B, DelayQueue must implement the compareTo() and getDelay() methods. C. The getDelay method returns the time remaining before the element expires, when <=0When the element is invalidated, it can be retrieved from the queue.Copy the code

Why use leader/follower mode here?

  • If it is not the first node, there is no need to wake up at all!
  • If the value is set before the delay is up, you need to wait, but at this time, a new element with a shorter delay is added to the queue, and it is placed at the head of the queue, then the for loop starts, and the element that is added is obtained, and the wait before is in vain. Obviously, you can exit the wait earlier!
  • There is if good multithreading are waiting in this, if the time is up, at the same time good multithreading will charge waiting queue into the lock pool, to compete for lock resources, but the result can only be a success, many write fearless competition! (Multiple waits and awakenings)

2.3 the Timer and TimerTask

  • Sorting in TaskQueue is heap sorting of the next execution time in the TimerTask, fetching the first array at a time.
  • DelayQueue sorts the results of getDelay() of the elements in the queue

Timer is a Timer tool used to schedule the execution of a specified task in a background thread. It can be scheduled to perform a task once or repeatedly. Main methods:

2.4 Time Wheel (Kafka)

Time wheel

  • Time lattice: the block in a circular structure used to store delayed tasks;
  • Pointer (CurrentTime) : points to the time cell of the current operation, representing the CurrentTime
  • TicksPerWheel: indicates the number of time bars in the time wheel
  • TickDuration: The interval between each time cell
  • Interval: indicates the total interval of the current time wheel, that is, ticksPerWheel*tickDuration

Based on the expiration time of each TimerTaskEntry and the time of the current time round, select an appropriate bucket(actually the TimerTaskList) and place the TimerTaskEntry object in it. Also, if the expiration time of the bucket is updated, Push the bucket into the DelayQueue and reorder it

Example: It is assumed that the time cell or bucket numbered 0 stores the task whose expiration time is T and each tick duration is 20ms. This cell can only store tasks whose expiration time is [t~t+20]ms. It is assumed that there are n time cells in the time round. If the interval is 1ms and the expiration time is m(ms), then the calculation formula M %n = time cell or bucket, for example, n=10,m=34ms, then the bucket or time cell is 4

2.5 RabbitMQ- Delayed tasks

RabbitMQ does not support delay queuing directly, but it can be simulated using the following features.

RabbitMQ can set x-message-tt for Queue and Message to control the lifetime of messages. If a Message times out, it will become a dead letter. RabbitMQ can set the expiration time of messages in the Queue in two ways. A: By setting the queue properties, all messages in the queue have the same expiration time. B: The TTL of each message can be different.

2.6 Quartz

Why not use a Timer?

  • Timers have no persistence mechanism.
  • Timers are not flexible (only the start time and repetition interval can be set, not based on time, date, day, etc.)
  • Timers do not take advantage of the thread pool, Timers one thread at a time
  • Timers have no real management plan

Core concepts: schedulers, tasks, and triggers.

The scheduler is responsible for scheduling each task. At a certain moment or after a certain time, the trigger is triggered and the specific task will start to execute.

  1. Scheduler is a scheduler container (headquarters), which can hold many jobdetails and triggers. When the container is started, each JobDetail in the container will be executed automatically according to the trigger.
  2. JobDetail is an executable job that is itself stateful.
  3. Trigger means when to Trigger.
  4. When the JobDetail and Trigger are registered with the Scheduler container, the assembled job (the JobDetail and Trigger pair) can be scheduled for execution when the container starts.
  5. Scheduler is a container that has a pool of threads that schedule each job in parallel to make the container more efficient.

To be continued…

If you have any questions above you can pay attention to the public number, to discuss with me, pay attention to the latest mass Java learning materials video, and the latest interview materials.

If you think this article is helpful to you, or if you have any questions you want to provide 1V1 free VIP service, you can pay attention to my public number, pay attention to the latest massive Java learning materials video, and the latest interview materials, your attention and forwarding is the biggest support for me, O(∩_∩)O: