In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "how to use DelayQueue in springboot delay tasks". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how to use DelayQueue in springboot execution delay tasks".
Introduction to DelayQueue
DelayQueue is an unbounded blocking queue from which elements can be extracted only when the delay expires. The header of the queue is the delay element that has been preserved for the longest time after the delay expires.
In many scenarios, we need to use a delay task, such as notifying the user when the asynchronous transfer operation expires, and canceling the order if the customer fails to pay within how long after placing the order, all of which can be realized by using the delay task.
DelayQueue in jdk can achieve the above requirements, and as the name implies, DelayQueue is a delay queue.
DelayQueue provides the ability to get queue elements at a specified time, and queue header elements are the ones closest to expiration.
If there is no expired element, using the poll () method returns a null value, and the timeout decision is determined by the return value of the getDelay (TimeUnit.NANOSECONDS) method is less than or equal to 0.
Delay queues cannot store empty elements.
The take () method is generally used to block the wait and continue when there are expired elements.
Queue element description
The queue element of DelayQueue needs to implement the Delayed interface, which is defined as follows:
Public interface Delayed extends Comparable {/ * * Returns the remaining delay associated with this object, in the * given time unit. * * @ param unit the time unit * @ return the remaining delay; zero or negative values indicate * that the delay has already elapsed * / long getDelay (TimeUnit unit);}
So the elements of DelayQueue need to implement the getDelay method and the compareTo method of the Comparable interface, the getDelay method to determine whether the elements are out of date, and the compareTo method to determine the order.
Application of examples in springboot
DelayTask is the element in the queue
Import java.util.Date;import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit;public class DelayTask implements Delayed {final private TaskBase data; final private long expire; / * construct deferred task * @ param data Business data * @ param expire Task delay time (ms) * / public DelayTask (TaskBase data, long expire) {super (); this.data = data; this.expire = expire + System.currentTimeMillis ();} public TaskBase getData () {return data } public long getExpire () {return expire;} @ Override public boolean equals (Object obj) {if (obj instanceof DelayTask) {return this.data.getIdentifier () .equals (DelayTask) obj) .getData () .getIdentifier ());} return false;} @ Override public String toString () {return "{" + "data:" + data.toString () + "," + "expire:" + new Date (expire) + "}" @ Override public long getDelay (TimeUnit unit) {return unit.convert (this.expire-System.currentTimeMillis (), unit);} @ Override public int compareTo (Delayed o) {long delta = getDelay (TimeUnit.NANOSECONDS)-o.getDelay (TimeUnit.NANOSECONDS); return (int) delta;}}
The TaskBase class is a user-defined business data base class, in which there is an identifier field to identify the id of the task for easy indexing.
Import com.alibaba.fastjson.JSON;public class TaskBase {private String identifier; public TaskBase (String identifier) {this.identifier = identifier;} public String getIdentifier () {return identifier;} public void setIdentifier (String identifier) {this.identifier = identifier;} @ Override public String toString () {return JSON.toJSONString (this);}}
Define a deferred task management class DelayQueueManager, add it to spring through @ Component annotation, and use @ Autowire injection where needed
Import com.alibaba.fastjson.JSON;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;import java.text.SimpleDateFormat;import java.util.Date;import java.util.concurrent.DelayQueue;import java.util.concurrent.Executors;@Componentpublic class DelayQueueManager implements CommandLineRunner {private final Logger logger = LoggerFactory.getLogger (DelayQueueManager.class); private DelayQueue delayQueue = new DelayQueue () / * join the delay queue * @ param task * / public void put (DelayTask task) {logger.info ("join delay tasks: {}", task); delayQueue.put (task);} / * cancel delay tasks * @ param task * @ return * / public boolean remove (DelayTask task) {logger.info ("cancel delay tasks: {}", task); return delayQueue.remove (task) } / * cancel deferred task * @ param taskid * @ return * / public boolean remove (String taskid) {return remove (new DelayTask (new TaskBase (taskid), 0));} @ Override public void run (String...) Args) throws Exception {logger.info ("initialize delay queue"); Executors.newSingleThreadExecutor (). Execute (new Thread (this::excuteThread));} / * deferred task execution thread * / private void excuteThread () {while (true) {try {DelayTask task = delayQueue.take (); processTask (task);} catch (InterruptedException e) {break * @ param task * / private void processTask (DelayTask task) {logger.info ("execute deferred task: {}", task); / / handle related logic based on data custom data in task, such as if (task.getData () instanceof XXX) {}}
DelayQueueManager implements the CommandLineRunner interface, and the run method is automatically called after the springboot is started.
The above is all the contents of the article "how to use DelayQueue in springboot execution delay tasks". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.