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

  • 生成订单30分钟未支付,则自动取消;
  • 生成订单60秒后,给用户发短信;

延时任务和定时任务的区别究竟在哪里呢?一共有如下几点区别:

  1. 定时任务有明确的触发时间,延时任务没有;
  2. 定时任务有执行周期,而延时任务在某事件触发后一段时间内执行,没有执行周期;
  3. 定时任务一般执行的是批处理操作是多个任务,而延时任务一般是单个任务

    方案分析

    1、数据库轮询

    思路

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

    实现

    可以用quartz来实现的,maven项目引入一个依赖如下所示:

    1. <dependency>
    2. <groupId>org.quartz-scheduler</groupId>
    3. <artifactId>quartz</artifactId>
    4. <version>2.2.2</version>
    5. </dependency>

    调用Demo类MyJob如下所示:

    1. public class MyJob implements Job {
    2. public void execute(JobExecutionContext context)
    3. throws JobExecutionException {
    4. System.out.println("要去数据库扫描啦。。。");
    5. }
    6. public static void main(String[] args) throws Exception {
    7. // 创建任务
    8. JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
    9. .withIdentity("job1", "group1").build();
    10. // 创建触发器 每3秒钟执行一次
    11. Trigger trigger = TriggerBuilder
    12. .newTrigger()
    13. .withIdentity("trigger1", "group3")
    14. .withSchedule(
    15. SimpleScheduleBuilder.simpleSchedule()
    16. .withIntervalInSeconds(3).repeatForever())
    17. .build();
    18. Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    19. // 将任务及其触发器放入调度器
    20. scheduler.scheduleJob(jobDetail, trigger);
    21. // 调度器开始调度任务
    22. scheduler.start();
    23. }
    24. }

    运行代码,可发现每隔3秒,输出:要去数据库扫描啦。。。

    优缺点

    优点:

  4. 简单易行,支持集群操作。

缺点:

  1. 对服务器内存消耗大;
  2. 存在延迟,比如你每隔3分钟扫描一次,那最坏的延迟时间就是3分钟;
  3. 假设你的订单有几千万条,每隔几分钟这样扫描一次,数据库损耗极大;

    2、JDK的延迟队列

    思路

    该方案是利用JDK自带的DelayQueue来实现,这是一个无界阻塞队列,该队列只有在延迟期满的时候才能从中获取元素,放入DelayQueue中的对象,是必须实现Delayed接口的。
    DelayedQueue实现工作流程如下图所示:
    生成订单 30 分钟未支付,则自动取消,该怎么实现? - 图1 ```java Poll():获取并移除队列的超时元素,没有则返回空

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

  1. <a name="VqIPn"></a>
  2. ### 实现
  3. 定义一个类`OrderDelay`实现`Delayed`,代码如下:
  4. ```java
  5. public class OrderDelay implements Delayed {
  6. private String orderId;
  7. private long timeout;
  8. OrderDelay(String orderId, long timeout) {
  9. this.orderId = orderId;
  10. this.timeout = timeout + System.nanoTime();
  11. }
  12. public int compareTo(Delayed other) {
  13. if (other == this) return 0;
  14. OrderDelay t = (OrderDelay) other;
  15. long d = (getDelay(TimeUnit.NANOSECONDS) - t.getDelay(TimeUnit.NANOSECONDS));
  16. return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
  17. }
  18. // 返回距离你自定义的超时时间还有多
  19. public long getDelay(TimeUnit unit) {
  20. return unit.convert(timeout - System.nanoTime(),TimeUnit.NANOSECONDS);
  21. }
  22. void print() {
  23. System.out.println(orderId+"编号的订单要删除啦。。。。");
  24. }
  25. }

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

  1. public class DelayQueueDemo {
  2. public static void main(String[] args) {
  3. // TODO Auto-generated method stub
  4. List<String> list = new ArrayList<String>();
  5. list.add("00000001");
  6. list.add("00000002");
  7. list.add("00000003");
  8. list.add("00000004");
  9. list.add("00000005");
  10. DelayQueue<OrderDelay> queue = newDelayQueue<OrderDelay>();
  11. long start = System.currentTimeMillis();
  12. for(int i = 0;i<5;i++){
  13. //延迟三秒取出
  14. queue.put(new OrderDelay(list.get(i),
  15. TimeUnit.NANOSECONDS.convert(3,TimeUnit.SECONDS)));
  16. try {
  17. queue.take().print();
  18. System.out.println("After " +
  19. (System.currentTimeMillis()-start) + " MilliSeconds");
  20. } catch (InterruptedException e) {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. }
  24. }
  25. }
  26. }

输出如下:

  1. 00000001编号的订单要删除啦。。。。
  2. After 3003 MilliSeconds
  3. 00000002编号的订单要删除啦。。。。
  4. After 6006 MilliSeconds
  5. 00000003编号的订单要删除啦。。。。
  6. After 9006 MilliSeconds
  7. 00000004编号的订单要删除啦。。。。
  8. After 12008 MilliSeconds
  9. 00000005编号的订单要删除啦。。。。
  10. After 15009 MilliSeconds

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

优缺点

优点:

  1. 效率高,任务触发时间延迟低。

缺点:

  1. 服务器重启后,数据全部消失,怕宕机;
  2. 集群扩展相当麻烦;
  3. 因为内存条件限制的原因,比如下单未付款的订单数太多,那么很容易就出现OOM异常;
  4. 代码复杂度较高;

    3、时间轮算法

    思路

    先上一张时间轮的图(这图到处都是啦)
    生成订单 30 分钟未支付,则自动取消,该怎么实现? - 图2
    时间轮算法可以类比于时钟,如上图箭头(
    时间轮算法可以类比于时钟,如上图箭头(指针)按某一个方向按固定频率轮动,每一次跳动称为一个 tick。这样可以看出定时轮由个3个重要的属性参数,ticksPerWheel(一轮的tick数),tickDuration(一个tick的持续时间)以及 timeUnit(时间单位),例如当ticksPerWheel=60,tickDuration=1,timeUnit=秒,这就和现实中的始终的秒针走动完全类似了。
    如果当前指针指在1上面,我有一个任务需要4秒以后执行,那么这个执行的线程回调或者消息将会被放在5上。那如果需要在20秒之后执行怎么办,由于这个环形结构槽数只到8,如果要20秒,指针需要多转2圈。位置是在2圈之后的5上面(20 % 8 + 1);

    实现

    我们用NettyHashedWheelTimer来实现,给Pom加上下面的依赖:

    1. <dependency>
    2. <groupId>io.netty</groupId>
    3. <artifactId>netty-all</artifactId>
    4. <version>4.1.24.Final</version>
    5. </dependency>

    测试代码HashedWheelTimerTest如下所示:

    1. public class HashedWheelTimerTest {
    2. static class MyTimerTask implements TimerTask{
    3. boolean flag;
    4. public MyTimerTask(boolean flag){
    5. this.flag = flag;
    6. }
    7. public void run(Timeout timeout) throws Exception {
    8. // TODO Auto-generated method stub
    9. System.out.println("要去数据库删除订单了。。。。");
    10. this.flag =false;
    11. }
    12. }
    13. public static void main(String[] argv) {
    14. MyTimerTask timerTask = new MyTimerTask(true);
    15. Timer timer = new HashedWheelTimer();
    16. timer.newTimeout(timerTask, 5, TimeUnit.SECONDS);
    17. int i = 1;
    18. while(timerTask.flag){
    19. try {
    20. Thread.sleep(1000);
    21. } catch (InterruptedException e) {
    22. // TODO Auto-generated catch block
    23. e.printStackTrace();
    24. }
    25. System.out.println(i+"秒过去了");
    26. i++;
    27. }
    28. }
    29. }

    输出如下:

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

    优缺点

    优点:

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

缺点:

  1. 服务器重启后,数据全部消失,怕宕机;
  2. 集群扩展相当麻烦;
  3. 因为内存条件限制的原因,比如下单未付款的订单数太多,那么很容易就出现OOM异常;

    4、redis

    思路一

    利用rediszsetzset是一个有序集合,每一个元素(member)都关联了一个score,通过score排序来取集合中的值。
    1. 添加元素:ZADD key score member [[score member] [score member] …]
    2. 按顺序查询元素:ZRANGE key start stop [WITHSCORES]
    3. 查询元素score:ZSCORE key member
    4. 移除元素:ZREM key member [member …]
    测试如下: ```cpp //添加单个元素 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 WITHSCORES 1) “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 WITHSCORES 1) “bing.com” 2) “8” 3) “baidu.com” 4) “9”

  1. 那么如何实现呢?我们将订单超时时间戳与订单号分别设置为`score``member`,系统扫描第一个元素判断是否超时,具体如下图所示:<br />![](https://cdn.nlark.com/yuque/0/2022/webp/12791373/1651586712470-80d719b1-c9c6-4091-bca6-5ba2462acd24.webp#clientId=u5f2d549a-ba84-4&crop=0&crop=0&crop=1&crop=1&from=paste&id=ubf404358&margin=%5Bobject%20Object%5D&originHeight=411&originWidth=824&originalType=url&ratio=1&rotation=0&showTitle=false&status=done&style=none&taskId=u882057ba-412c-46d0-8dbe-d1e91f344fc&title=)
  2. <a name="zakFp"></a>
  3. ### 实现一
  4. ```java
  5. public class AppTest {
  6. private static final String ADDR = "127.0.0.1";
  7. private static final int PORT = 6379;
  8. private static JedisPool jedisPool = new JedisPool(ADDR, PORT);
  9. public static Jedis getJedis() {
  10. return jedisPool.getResource();
  11. }
  12. //生产者,生成5个订单放进去
  13. public void productionDelayMessage(){
  14. for(int i=0;i<5;i++){
  15. //延迟3秒
  16. Calendar cal1 = Calendar.getInstance();
  17. cal1.add(Calendar.SECOND, 3);
  18. int second3later = (int) (cal1.getTimeInMillis() / 1000);
  19. AppTest.getJedis().zadd("OrderId",second3later,"OID0000001"+i);
  20. System.out.println(System.currentTimeMillis()+"ms:redis生成了一个订单任务:订单ID为"+"OID0000001"+i);
  21. }
  22. }
  23. //消费者,取订单
  24. public void consumerDelayMessage(){
  25. Jedis jedis = AppTest.getJedis();
  26. while(true){
  27. Set<Tuple> items = jedis.zrangeWithScores("OrderId", 0, 1);
  28. if(items == null || items.isEmpty()){
  29. System.out.println("当前没有等待的任务");
  30. try {
  31. Thread.sleep(500);
  32. } catch (InterruptedException e) {
  33. // TODO Auto-generated catch block
  34. e.printStackTrace();
  35. }
  36. continue;
  37. }
  38. int score = (int) ((Tuple)items.toArray()[0]).getScore();
  39. Calendar cal = Calendar.getInstance();
  40. int nowSecond = (int) (cal.getTimeInMillis() / 1000);
  41. if(nowSecond >= score){
  42. String orderId = ((Tuple)items.toArray()[0]).getElement();
  43. jedis.zrem("OrderId", orderId);
  44. System.out.println(System.currentTimeMillis() +"ms:redis消费了一个任务:消费的订单OrderId为"+orderId);
  45. }
  46. }
  47. }
  48. public static void main(String[] args) {
  49. AppTest appTest =new AppTest();
  50. appTest.productionDelayMessage();
  51. appTest.consumerDelayMessage();
  52. }
  53. }

此时对应输出如下:
生成订单 30 分钟未支付,则自动取消,该怎么实现? - 图3
可以看到,几乎都是3秒之后,消费订单。
然而,这一版存在一个致命的硬伤,在高并发条件下,多消费者会取到同一个订单号,我们上测试代码。

  1. public class ThreadTest {
  2. private static final int threadNum = 10;
  3. private static CountDownLatch cdl = newCountDownLatch(threadNum);
  4. static class DelayMessage implements Runnable{
  5. public void run() {
  6. try {
  7. cdl.await();
  8. } catch (InterruptedException e) {
  9. // TODO Auto-generated catch block
  10. e.printStackTrace();
  11. }
  12. AppTest appTest =new AppTest();
  13. appTest.consumerDelayMessage();
  14. }
  15. }
  16. public static void main(String[] args) {
  17. AppTest appTest =new AppTest();
  18. appTest.productionDelayMessage();
  19. for(int i=0;i<threadNum;i++){
  20. new Thread(new DelayMessage()).start();
  21. cdl.countDown();
  22. }
  23. }
  24. }

输出如下所示:
生成订单 30 分钟未支付,则自动取消,该怎么实现? - 图4
显然,出现了多个线程消费同一个资源的情况。
解决方案:

  1. 用分布式锁,但是用分布式锁,性能下降了,该方案不细说。
  2. 对ZREM的返回值进行判断,只有大于0的时候,才消费数据,于是将consumerDelayMessage()方法里的

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

    修改为:

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

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

    思路二

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

    实现二

    在redis.conf中,加入一条配置notify-keyspace-events Ex
    运行代码如下:

    1. public class RedisTest {
    2. private static final String ADDR = "127.0.0.1";
    3. private static final int PORT = 6379;
    4. private static JedisPool jedis = new JedisPool(ADDR, PORT);
    5. private static RedisSub sub = new RedisSub();
    6. public static void init() {
    7. new Thread(new Runnable() {
    8. public void run() {
    9. jedis.getResource().subscribe(sub, "__keyevent@0__:expired");
    10. }
    11. }).start();
    12. }
    13. public static void main(String[] args) throws InterruptedException {
    14. init();
    15. for(int i =0;i<10;i++){
    16. String orderId = "OID000000"+i;
    17. jedis.getResource().setex(orderId, 3, orderId);
    18. System.out.println(System.currentTimeMillis()+"ms:"+orderId+"订单生成");
    19. }
    20. }
    21. static class RedisSub extends JedisPubSub {
    22. @Override
    23. public void onMessage(String channel, String message) {
    24. System.out.println(System.currentTimeMillis()+"ms:"+message+"订单取消");
    25. }
    26. }
    27. }

    输出如下:
    生成订单 30 分钟未支付,则自动取消,该怎么实现? - 图5
    可以明显看到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可以针对QueueMessage设置 x-message-tt,来控制消息的生存时间,如果超时,则消息变为dead letter
    RabbitMQQueue可以配置x-dead-letter-exchangex-dead-letter-routing-key(可选)两个参数,用来控制队列内出现了deadletter,则按照这两个参数重新路由。结合以上两个特性,就可以模拟出延迟消息的功能。

    优缺点

    优点:

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

缺点:

  1. 本身的易用度要依赖于RabbitMQ的运维,因为要引用RabbitMQ,所以复杂度和成本变高。