延时任务实现方案总结(代码片段)

HelloWorld搬运工 HelloWorld搬运工     2023-03-09     800

关键词:

# 引言

在开发中,往往会遇到一些关于延时任务的需求。例如

  • 生成订单30分钟未支付,则自动取消

  • 生成订单60秒后,给用户发短信

对上述的任务,我们给一个专业的名字来形容,那就是延时任务。那么这里就会产生一个问题,这个延时任务和定时任务的区别究竟在哪里呢?一共有如下几点区别

  1. 定时任务有明确的触发时间,延时任务没有

  2. 定时任务有执行周期,而延时任务在某事件触发后一段时间内执行,没有执行周期

  3. 定时任务一般执行的是批处理操作是多个任务,而延时任务一般是单个任务

下面,我们以判断订单是否超时为例,进行方案分析

# 方案分析

(1)数据库轮询

思路

该方案通常是在小型项目中使用,即通过一个线程定时的去扫描数据库,通过订单时间来判断是否有超时的订单,然后进行update或delete等操作

实现

博主当年早期是用quartz来实现的(实习那会的事),简单介绍一下


maven项目引入一个依赖如下所示

    <dependency>        <groupId>org.quartz-scheduler</groupId>        <artifactId>quartz</artifactId>        <version>2.2.2</version>    </dependency>

调用Demo类MyJob如下所示

package com.rjzheng.delay1; import org.quartz.JobBuilder;import org.quartz.JobDetail;import org.quartz.Scheduler;import org.quartz.SchedulerException;import org.quartz.SchedulerFactory;import org.quartz.SimpleScheduleBuilder;import org.quartz.Trigger;import org.quartz.TriggerBuilder;import org.quartz.impl.StdSchedulerFactory;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException; public class MyJob implements Job     public void execute(JobExecutionContext context)            throws JobExecutionException         System.out.println("要去数据库扫描啦。。。");         public static void main(String[] args) throws Exception         // 创建任务        JobDetail jobDetail = JobBuilder.newJob(MyJob.class)                .withIdentity("job1", "group1").build();        // 创建触发器 每3秒钟执行一次        Trigger trigger = TriggerBuilder                .newTrigger()                .withIdentity("trigger1", "group3")                .withSchedule(                        SimpleScheduleBuilder.simpleSchedule()                                .withIntervalInSeconds(3).repeatForever())                .build();        Scheduler scheduler = new StdSchedulerFactory().getScheduler();        // 将任务及其触发器放入调度器        scheduler.scheduleJob(jobDetail, trigger);        // 调度器开始调度任务        scheduler.start();    

运行代码,可发现每隔3秒,输出如下

要去数据库扫描啦。。。

优缺点

优点:简单易行,支持集群操作

缺点:

(1)对服务器内存消耗大

(2)存在延迟,比如你每隔3分钟扫描一次,那最坏的延迟时间就是3分钟

(3)假设你的订单有几千万条,每隔几分钟这样扫描一次,数据库损耗极大

(2)JDK的延迟队列

思路

该方案是利用JDK自带的DelayQueue来实现,这是一个无界阻塞队列,该队列只有在延迟期满的时候才能从中获取元素,放入DelayQueue中的对象,是必须实现Delayed接口的。


DelayedQueue实现工作流程如下图所示

其中Poll():获取并移除队列的超时元素,没有则返回空


take():获取并移除队列的超时元素,如果没有则wait当前线程,直到有元素满足超时条件,返回结果。

实现

定义一个类OrderDelay实现Delayed,代码如下

package com.rjzheng.delay2; import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit; public class OrderDelay implements Delayed         private String orderId;    private long timeout;     OrderDelay(String orderId, long timeout)         this.orderId = orderId;        this.timeout = timeout + System.nanoTime();         public int compareTo(Delayed other)         if (other == this)            return 0;        OrderDelay t = (OrderDelay) other;        long d = (getDelay(TimeUnit.NANOSECONDS) - t                .getDelay(TimeUnit.NANOSECONDS));        return (d == 0) ? 0 : ((d < 0) ? -1 : 1);         // 返回距离你自定义的超时时间还有多少    public long getDelay(TimeUnit unit)         return unit.convert(timeout - System.nanoTime(),TimeUnit.NANOSECONDS);         void print()         System.out.println(orderId+"编号的订单要删除啦。。。。");    

运行的测试Demo为,我们设定延迟时间为3秒

package com.rjzheng.delay2; import java.util.ArrayList;import java.util.List;import java.util.concurrent.DelayQueue;import java.util.concurrent.TimeUnit; public class DelayQueueDemo      public static void main(String[] args)               // TODO Auto-generated method stub              List<String> list = new ArrayList<String>();              list.add("00000001");              list.add("00000002");              list.add("00000003");              list.add("00000004");              list.add("00000005");              DelayQueue<OrderDelay> queue = newDelayQueue<OrderDelay>();              long start = System.currentTimeMillis();              for(int i = 0;i<5;i++)                  //延迟三秒取出                queue.put(new OrderDelay(list.get(i),                          TimeUnit.NANOSECONDS.convert(3,TimeUnit.SECONDS)));                      try                            queue.take().print();                           System.out.println("After " +                                   (System.currentTimeMillis()-start) + " MilliSeconds");                   catch (InterruptedException e)                       // TODO Auto-generated catch block                      e.printStackTrace();                                                

输出如下​​​​​​​

00000001编号的订单要删除啦。。。。After 3003 MilliSeconds00000002编号的订单要删除啦。。。。After 6006 MilliSeconds00000003编号的订单要删除啦。。。。After 9006 MilliSeconds00000004编号的订单要删除啦。。。。After 12008 MilliSeconds00000005编号的订单要删除啦。。。。After 15009 MilliSeconds

可以看到都是延迟3秒,订单被删除

优缺点

优点:效率高,任务触发时间延迟低。


缺点:

(1)服务器重启后,数据全部消失,怕宕机


(2)集群扩展相当麻烦


(3)因为内存条件限制的原因,比如下单未付款的订单数太多,那么很容易就出现OOM异常


(4)代码复杂度较高

(3)时间轮算法

思路

先上一张时间轮的图(这图到处都是啦)

时间轮算法可以类比于时钟,如上图箭头(指针)按某一个方向按固定频率轮动,每一次跳动称为一个 tick。这样可以看出定时轮由个3个重要的属性参数,ticksPerWheel(一轮的tick数),tickDuration(一个tick的持续时间)以及 timeUnit(时间单位),例如当ticksPerWheel=60,tickDuration=1,timeUnit=秒,这就和现实中的始终的秒针走动完全类似了。

如果当前指针指在1上面,我有一个任务需要4秒以后执行,那么这个执行的线程回调或者消息将会被放在5上。那如果需要在20秒之后执行怎么办,由于这个环形结构槽数只到8,如果要20秒,指针需要多转2圈。位置是在2圈之后的5上面(20 % 8 + 1)

实现

我们用Netty的HashedWheelTimer来实现


给Pom加上下面的依赖​​​​​​​

        <dependency>            <groupId>io.netty</groupId>            <artifactId>netty-all</artifactId>            <version>4.1.24.Final</version>        </dependency>

测试代码HashedWheelTimerTest如下所示​​​​​​​

package com.rjzheng.delay3; import io.netty.util.HashedWheelTimer;import io.netty.util.Timeout;import io.netty.util.Timer;import io.netty.util.TimerTask; import java.util.concurrent.TimeUnit; public class HashedWheelTimerTest     static class MyTimerTask implements TimerTask        boolean flag;        public MyTimerTask(boolean flag)            this.flag = flag;                public void run(Timeout timeout) throws Exception             // TODO Auto-generated method stub             System.out.println("要去数据库删除订单了。。。。");             this.flag =false;                public static void main(String[] argv)         MyTimerTask timerTask = new MyTimerTask(true);        Timer timer = new HashedWheelTimer();        timer.newTimeout(timerTask, 5, TimeUnit.SECONDS);        int i = 1;        while(timerTask.flag)            try                 Thread.sleep(1000);             catch (InterruptedException e)                 // TODO Auto-generated catch block                e.printStackTrace();                        System.out.println(i+"秒过去了");            i++;            

输出如下

1秒过去了2秒过去了3秒过去了4秒过去了5秒过去了要去数据库删除订单了。。。。6秒过去了

优缺点

优点:效率高,任务触发时间延迟时间比delayQueue低,代码复杂度比delayQueue低。

缺点:

(1)服务器重启后,数据全部消失,怕宕机

(2)集群扩展相当麻烦

(3)因为内存条件限制的原因,比如下单未付款的订单数太多,那么很容易就出现OOM异常

(4)redis缓存

思路一

利用redis的zset,zset是一个有序集合,每一个元素(member)都关联了一个score,通过score排序来取集合中的值

 zset常用命令

  • 添加元素:ZADD key score member [[score member] [score member] …]

  • 按顺序查询元素:ZRANGE key start stop [WITHSCORES]

  • 查询元素score:ZSCORE key member

  • 移除元素:ZREM key member [member …]

测试如下

# 添加单个元素 redis> ZADD page_rank 10 google.com(integer) 1  # 添加多个元素 redis> ZADD page_rank 9 baidu.com 8 bing.com(integer) 2 redis> ZRANGE page_rank 0 -1 WITHSCORES1) "bing.com"2) "8"3) "baidu.com"4) "9"5) "google.com"6) "10" # 查询元素的score值redis> ZSCORE page_rank bing.com"8" # 移除单个元素 redis> ZREM page_rank google.com(integer) 1 redis> ZRANGE page_rank 0 -1 WITHSCORES1) "bing.com"2) "8"3) "baidu.com"4) "9"

那么如何实现呢?我们将订单超时时间戳与订单号分别设置为score和member,系统扫描第一个元素判断是否超时,具体如下图所示

实现一

package com.rjzheng.delay4; import java.util.Calendar;import java.util.Set; import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.Tuple; public class AppTest     private static final String ADDR = "127.0.0.1";    private static final int PORT = 6379;    private static JedisPool jedisPool = new JedisPool(ADDR, PORT);        public static Jedis getJedis()        return jedisPool.getResource();            //生产者,生成5个订单放进去    public void productionDelayMessage()        for(int i=0;i<5;i++)            //延迟3秒            Calendar cal1 = Calendar.getInstance();            cal1.add(Calendar.SECOND, 3);            int second3later = (int) (cal1.getTimeInMillis() / 1000);            AppTest.getJedis().zadd("OrderId",second3later,"OID0000001"+i);            System.out.println(System.currentTimeMillis()+"ms:redis生成了一个订单任务:订单ID为"+"OID0000001"+i);                    //消费者,取订单    public void consumerDelayMessage()        Jedis jedis = AppTest.getJedis();        while(true)            Set<Tuple> items = jedis.zrangeWithScores("OrderId", 0, 1);            if(items == null || items.isEmpty())                System.out.println("当前没有等待的任务");                try                     Thread.sleep(500);                 catch (InterruptedException e)                     // TODO Auto-generated catch block                    e.printStackTrace();                                continue;                        int  score = (int) ((Tuple)items.toArray()[0]).getScore();            Calendar cal = Calendar.getInstance();            int nowSecond = (int) (cal.getTimeInMillis() / 1000);            if(nowSecond >= score)                String orderId = ((Tuple)items.toArray()[0]).getElement();                jedis.zrem("OrderId", orderId);                System.out.println(System.currentTimeMillis() +"ms:redis消费了一个任务:消费的订单OrderId为"+orderId);                                public static void main(String[] args)         AppTest appTest =new AppTest();        appTest.productionDelayMessage();        appTest.consumerDelayMessage();        

此时对应输出如下

可以看到,几乎都是3秒之后,消费订单。

然而,这一版存在一个致命的硬伤,在高并发条件下,多消费者会取到同一个订单号,我们上测试代码ThreadTest

package com.rjzheng.delay4; import java.util.concurrent.CountDownLatch; public class ThreadTest     private static final int threadNum = 10;    private static CountDownLatch cdl = newCountDownLatch(threadNum);    static class DelayMessage implements Runnable        public void run()             try                 cdl.await();             catch (InterruptedException e)                 // TODO Auto-generated catch block                e.printStackTrace();                        AppTest appTest =new AppTest();            appTest.consumerDelayMessage();                public static void main(String[] args)         AppTest appTest =new AppTest();        appTest.productionDelayMessage();        for(int i=0;i<threadNum;i++)            new Thread(new DelayMessage()).start();            cdl.countDown();            

输出如下所示

显然,出现了多个线程消费同一个资源的情况。

解决方案

(1)用分布式锁,但是用分布式锁,性能下降了,该方案不细说。

(2)对ZREM的返回值进行判断,只有大于0的时候,才消费数据,于是将consumerDelayMessage()方法里的

if(nowSecond >= score)    String orderId = ((Tuple)items.toArray()[0]).getElement();    jedis.zrem("OrderId", orderId);    System.out.println(System.currentTimeMillis()+"ms:redis消费了一个任务:消费的订单OrderId为"+orderId);

修改为

if(nowSecond >= score)    String orderId = ((Tuple)items.toArray()[0]).getElement();    Long num = jedis.zrem("OrderId", orderId);    if( num != null && num>0)        System.out.println(System.currentTimeMillis()+"ms:redis消费了一个任务:消费的订单OrderId为"+orderId);    

在这种修改后,重新运行ThreadTest类,发现输出正常了

思路二

该方案使用redis的Keyspace Notifications,中文翻译就是键空间机制,就是利用该机制可以在key失效之后,提供一个回调,实际上是redis会给客户端发送一个消息。是需要redis版本2.8以上。

实现二

在redis.conf中,加入一条配置

notify-keyspace-events Ex

运行代码如下

package com.rjzheng.delay5; import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPubSub; public class RedisTest     private static final String ADDR = "127.0.0.1";    private static final int PORT = 6379;    private static JedisPool jedis = new JedisPool(ADDR, PORT);    private static RedisSub sub = new RedisSub();     public static void init()         new Thread(new Runnable()             public void run()                 jedis.getResource().subscribe(sub, "__keyevent@0__:expired");                    ).start();         public static void main(String[] args) throws InterruptedException         init();        for(int i =0;i<10;i++)            String orderId = "OID000000"+i;            jedis.getResource().setex(orderId, 3, orderId);            System.out.println(System.currentTimeMillis()+"ms:"+orderId+"订单生成");                    static class RedisSub extends JedisPubSub         <ahref='http://www.jobbole.com/members/wx610506454'>@Override</a>        public void onMessage(String channel, String message)             System.out.println(System.currentTimeMillis()+"ms:"+message+"订单取消");            

输出如下

可以明显看到3秒过后,订单取消了


ps:redis的pub/sub机制存在一个硬伤,官网内容如下

原:Because Redis Pub/Sub is fire and forget currently there is no way to use this feature if your application demands reliable notification of events, that is, if your Pub/Sub client disconnects, and reconnects later, all the events delivered during the time the client was disconnected are lost.


翻: Redis的发布/订阅目前是即发即弃(fire and forget)模式的,因此无法实现事件的可靠通知。也就是说,如果发布/订阅的客户端断链之后又重连,则在客户端断链期间的所有事件都丢失了。
因此,方案二不是太推荐。当然,如果你对可靠性要求不高,可以使用。

优缺点

优点:

(1)由于使用Redis作为消息通道,消息都存储在Redis中。如果发送程序或者任务处理程序挂了,重启之后,还有重新处理数据的可能性。


(2)做集群扩展相当方便


(3)时间准确度高
 

缺点:

(1)需要额外进行redis维护

(5)使用消息队列

我们可以采用rabbitMQ的延时队列。RabbitMQ具有以下两个特性,可以实现延迟队列

  • RabbitMQ可以针对Queue和Message设置 x-message-tt,来控制消息的生存时间,如果超时,则消息变为dead letter

  • lRabbitMQ的Queue可以配置x-dead-letter-exchange 和x-dead-letter-routing-key(可选)两个参数,用来控制队列内出现了deadletter,则按照这两个参数重新路由。
    结合以上两个特性,就可以模拟出延迟消息的功能,具体的,我改天再写一篇文章,这里再讲下去,篇幅太长。

优缺点

优点: 高效,可以利用rabbitmq的分布式特性轻易的进行横向扩展,消息支持持久化增加了可靠性。


缺点:本身的易用度要依赖于rabbitMq的运维.因为要引用rabbitMq,所以复杂度和成本变高

延迟任务的实现总结(代码片段)

延迟任务有别于定式任务,定式任务往往是固定周期的,有明确的触发时间。而延迟任务一般没有固定的开始时间,它常常是由一个事件触发的,而在这个事件触发之后的一段时间内触发另一个事件。延迟任务相关的业务场景如... 查看详情

基于rdisson实现延时队列,解决支付延时查单关单方案(代码片段)

基于Rdisson实现延时队列,解决支付延时查单、关单方案1.需求2.实现方式3.具体代码1.需求下单支付后,支付回调因部分因素不可达,导致订单状态与微信支付状态不一致。此时需要服务端主动查询订单支付状态,... 查看详情

java并发编程(十九):scheduledthreadpoolexecutor总结与源码分析(代码片段)

...PoolExecutor总结前言  ScheduledThreadPoolExecutor主要用于处理延时任务或者定时任务,在平时的工作场景中也有被广泛应用,而我们有了前文关于ThreadPoolExecutor源码的深入理解,这里理解ScheduledThreadPoolExecutor便会顺畅不少... 查看详情

每日一博-延时任务的多种实现方式解读(代码片段)

文章目录Pre延时任务VS定时任务SolutionsDB轮询核心思想DemoCode优缺点JDK的DelayQueue核心思想DemoCode优缺点时间轮算法核心思想DemoCode优缺点核心思想DemoCode优缺点Pre每日一博-使用环形队列实现高效的延时消息延时任务VS定时任务举个... 查看详情

订单30分钟未支付自动取消怎么实现?(代码片段)

...用消息队列了解需求在开发中,往往会遇到一些关于延时任务的需求。例如生成订单30分钟未支付,则自动取消生成订单60秒后,给用户发短信对上述的任务,我们给一个专业的名字来形容,那就是延时任务。那么... 查看详情

延时队列的几种实现方案(代码片段)

延时队列的特征它是一个队列是被延迟消费的(设定一个未来的某个时间点被消费)延时队列的应用场景订单成功后,在30分钟内没有支付,自动取消订单外卖平台发送订餐通知,下单成功后60s给用户推送短信... 查看详情

延时任务-基于rediszset的完整实现(代码片段)

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

千万级延时任务队列如何实现,看美图开源的-lmstfy(代码片段)

千万级延时任务队列如何实现,看美图开源的-LMSTFY导读:Task是web开发中一个经典场景,我们时常需要延时任务,或者定时任务,通常都需要任务队列。常见的任务队列如celery,lmstfy是美图开源的任务队列。本文作者详细剖析了l... 查看详情

rabbitmq延时队列实现定时任务(代码片段)

场景实际业务中对于定时任务的需求是不可避免的,例如,订单超时自动取消、每天定时拉取数据等,在Node.js中系统层面提供了setTimeout、setInterval两个API或通过node-schedule这种第三方库来实现。通过这种方式实现对于简单的定时... 查看详情

优雅实现延时任务之zookeeper篇(代码片段)

前言在《优雅实现延时任务之Redis篇》一文中提到,实现延时任务的关键点,是要存储任务的描述和任务的执行时间,还要能根据任务执行时间进行排序,那么我们可不可以使用zookeeper来实现延时任务呢?答案... 查看详情

基于rabbitmq实现分布式延时任务调度(代码片段)

一.分布式延时任务传统做法是将延时任务插入数据库,使用定时去扫描,比对任务是否到期,到期则执行并设置任务状态为完成。这种做法在分布式环境下还需要对定时扫描做特殊处理(加分布式锁)避免任务被重复执行。然... 查看详情

rabbitmq:伪延时队列(代码片段)

目录一、什么是延时队列二、RabbitMQ实现三、延时队列的问题四、解决RabbitMQ的伪延时方案ps:伪延时队列先卖个关子,我们先了解下延时队列。一、什么是延时队列所谓延时队列是指消息push到队列后,监听的消费者不能第一时间... 查看详情

executor框架周期/延时任务schedulethreadpoolexecutor(代码片段)

ScheduledThreadPoolExecutor介绍??ScheduledThreadPoolExecutor是一个可以实现定时任务的ThreadPoolExecutor(线程池)。比timer更加灵活,效率更高!//继承自ThreadPoolExecutor类,并实现了ScheduledExecutorService接口publicclassScheduledThreadPoolExecu 查看详情

springboot使用rabbitmq实现延时任务(代码片段)

延时队列顾名思义,即放置在该队列里面的消息是不需要立即消费的,而是等待一段时间之后取出消费。那么,为什么需要延迟消费呢?我们来看以下的场景订单业务:在电商/点餐中,都有下单后30分钟内没有付款,就自动取消... 查看详情

通过rabbitmq的direct模式以及死信队列实现延时任务(代码片段)

运用RabbitMQ的DIRECT模式以及死信队列实现延时操作以及不同间隔时间后重试一、原理描述图解:一条绑定路由为【FOR_QUEUE1】的消息被发送到交换机【EXCHANGE】上RabbitTemplate.convertSendAndReceive("EXCHANGE","FOR_QUEUE1","我... 查看详情

每日一博-使用环形队列实现高效的延时消息(代码片段)

文章目录Pre方案A方案B总结Pre来个场景:24小时后将未进行某个Action的业务,执行另外一个动作。比如24小时未付款的订单,取消。你可能会说方案A来个定时呗,每隔半小时,扫描数据库订单表,将完成时... 查看详情

python并发学习总结(代码片段)

目录一、理解操作系统二、任务类型三、Socket模块四、一个简单的C/S程序五、使用阻塞IO实现并发方案一:阻塞IO+多进程方案二:阻塞IO+多线程阻塞IO模型的思考和总结六、使用非阻塞IO实现并发方案一:非阻塞IO+Try+轮询方案二... 查看详情

springboot+redis实现延时队列,写得太好了!(代码片段)

来源:blog.csdn.net/qq330983778/article/details/99341671业务流程首先我们分析下这个流程用户提交任务。首先将任务推送至延迟队列中。延迟队列接收到任务后,首先将任务推送至jobpool中,然后计算其执行时间。然后生成延迟... 查看详情