DelayQueue简介

在很多场景我们需要用到延时任务,比如给客户异步转账操作超时后发通知告知用户,还有客户下单后多长时间内没支付则取消订单等等,这些都可以使用延时任务来实现。

jdk中DelayQueue可以实现上述需求,顾名思义DelayQueue就是延时队列。

DelayQueue提供了在指定时间才能获取队列元素的功能,队列头元素是最接近过期的元素。

没有过期元素的话,使用poll()方法会返回null值,超时判定是通过getDelay(TimeUnit.NANOSECONDS)方法的返回值小于等于0来判断。

延时队列不能存放空元素。

一般使用take()方法阻塞等待,有过期元素时继续。

队列元素说明

DelayQueue<E extends Delayed>的队列元素需要实现Delayed接口,该接口类定义如下:

public interface Delayed extends Comparable<Delayed> {

    /**
* 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);
}

所以DelayQueue的元素需要实现getDelay方法和Comparable接口的compareTo方法,getDelay方法来判定元素是否过期,compareTo方法来确定先后顺序。

springboot中实例运用

DelayTask就是队列中的元素

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; /**
* 构造延时任务
* @param data 业务数据
* @param expire 任务延时时间(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;
}
}
TaskBase类是用户自定义的业务数据基类,其中有一个identifier字段来标识任务的id,方便进行索引
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);
}
}

定义一个延时任务管理类DelayQueueManager,通过@Component注解加入到spring中管理,在需要使用的地方通过@Autowire注入

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; @Component
public class DelayQueueManager implements CommandLineRunner {
private final Logger logger = LoggerFactory.getLogger(DelayQueueManager.class);
private DelayQueue<DelayTask> delayQueue = new DelayQueue<>(); /**
* 加入到延时队列中
* @param task
*/
public void put(DelayTask task) {
logger.info("加入延时任务:{}", task);
delayQueue.put(task);
} /**
* 取消延时任务
* @param task
* @return
*/
public boolean remove(DelayTask task) {
logger.info("取消延时任务:{}", task);
return delayQueue.remove(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("初始化延时队列");
Executors.newSingleThreadExecutor().execute(new Thread(this::excuteThread));
} /**
* 延时任务执行线程
*/
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("执行延时任务:{}", task);
//根据task中的data自定义数据来处理相关逻辑,例 if (task.getData() instanceof XXX) {}
}
}

DelayQueueManager实现了CommandLineRunner接口,在springboot启动完成后就会自动调用run方法。

												

springboot执行延时任务-DelayQueue的使用的更多相关文章

  1. SpringBoot执行定时任务@Scheduled

    SpringBoot执行定时任务@Scheduled 在做项目时,需要一个定时任务来接收数据存入数据库,后端再写一个接口来提供该该数据的最新的那一条. 数据保持最新:设计字段sign的值(0,1)来设 ...

  2. ios想要取消执行延时调用的方法

    想要取消执行延时调用的方法: [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideDia ...

  3. SpringBoot执行原理

    目录 [Toc] 一.执行原理: 每个Spring Boot项目都有一个主程序启动类,在主程序启动类中有一个启动项目的main()方法, 在该方法中通过执行SpringApplication.run( ...

  4. springboot执行流程

    构造方法初始化,创建一个新的实例,这个应用程序的上下文要从指定的来源加载bean public SpringApplication(ResourceLoaderresourceLoader,Class ...

  5. SpringBoot执行定时任务

    1.在启动类中加入@EnableScheduling来开启定时任务. package com.example.demo; import org.springframework.boot.SpringA ...

  6. 分布式 redis 延时任务 基于 springboot 示例

    Lilishop 技术栈 官方公众号 & 开源不易,如有帮助请点Star 介绍 官网:https://pickmall.cn Lilishop 是一款Java开发,基于SpringBoot研发 ...

  7. iOS:延时执行的三种方式

    延时执行的三种方式:performSelectorXXX方法.GCD中延时函数.创建定时器   第一种方式:NSObject分类当中的方法,延迟一段时间调用某一个方法 @interface NSObj ...

  8. java并发编程工具类JUC第三篇:DelayQueue延时队列

    DelayQueue 是BlockingQueue接口的实现类,它根据"延时时间"来确定队列内的元素的处理优先级(即根据队列元素的"延时时间"进行排序).另一层 ...

  9. 延时任务-基于redis zset的完整实现

    所谓的延时任务给大家举个例子:你买了一张火车票,必须在30分钟之内付款,否则该订单被自动取消.订单30分钟不付款自动取消,这个任务就是一个延时任务. 我之前已经写过2篇关于延时任务的文章: <完 ...

随机推荐

  1. 原生JS实现队结构及利用队列模拟‘击鼓传花’游戏

    1. 前言 队列,是一种遵从先进先出(FIFO,First-In-First-Out)原则的有序集合.队列在尾部添加新元素,并从顶部移除元素,最新添加的元素必须排在队列的末尾. 2.功能说明 enqu ...

  2. 学习笔记 : python 文件操作

    1.如果文件路径带有   \ 比如  open('c:\python\test.txt') 会报:SyntaxError: (unicode error) 'unicodeescape' codec ...

  3. 如何在SqlServer中使用层级节点类型hierarchyid

    Sql Server2008开始新增的 hierarchyid 数据类型使存储和查询层次结构数据变得更为简单. 为了使用这个类型,笔者在此进行简单记录,同时为需要的朋友提供一个简单的参考. --获取层 ...

  4. liunx查看日志 | 最实用命令和方法

    1.业务系统访问量不是很大的时候,使用这个,有bug的地方操作下,直接看最后操作的日志 tail  -fn100  catalina.log   查询日志尾部最后100行的日志,并且随文件;   2. ...

  5. vue 单页面应用 app自适应方案

    本文是使用淘宝的方案进行布局开发的,遇到的问题是会对app内使用的第三方插件,当页面进行缩放后,比如高德地图中的文字会显得过小,我使用的方法就是手动的动每一个尺寸进行手动的px 到 rem的替换,而不 ...

  6. mybatis调用mysql的存储过程(procedure),实现查询操作(student表中的某个年级中的总人数 select (1) 或者 select (*))

    step1:在mysql cmd中新建存储过程: drop procedure if exists queryCountByGrade ; delimiter // -- 定义存储过程结束符号为// ...

  7. 网站搭建 - Linux虚拟系统 - 时间设置 - root密码修改 - 建站

    先试一下,如果不成的话,就不发表了. 下载织梦: 额,这个先还是不要下了. Linux是Apache + MySQL + PHP的套路,先下载吧,不摆图了,直接摆命令,我的是虚拟机,可能没有那么顺利. ...

  8. .NET单例模式快速学习应用

    单例模式属于设计模式中最简单的一个模式,在实际应用中也非常广泛,但可能是受到各类教程的影响,看到很多实现方式仍然沿用Java的那一套,其实在.NET中可以用更简洁的实现方式. 一.知识点介绍 核心目标 ...

  9. Windows下mysql的下载和安装

    下载: 1.下载地址:https://www.mysql.com/downloads/ 2.选择社区版:MySQL Community (GPL) Downloads » 3.MySQL Commun ...

  10. # & 等特殊字符会导致传参失败

    # & 等特殊字符会导致 post 传参失败 处理方法使用 encodeURIComponent 将字符串转化一下 实例 // toUpperCase() 转化为大写字母 var cateco ...