分布式定时任务 --- Redis

Redis实现分布式定时任务

通过 ZSet 实现定时任务的思路是,将定时任务存放到 ZSet 集合中,并且将过期时间存储到 ZSet 的 Score 字段中,然后通过一个无线循环来判断当前时间内是否有需要执行的定时任务,如果有则进行执行,具体实现代码如下:

import redis.clients.jedis.Jedis;
import utils.JedisUtils;
import java.time.Instant;
import java.util.Set;
public class DelayQueueExample {        
    private static final String _KEY = "DelayQueueExample";        
    public static void main(String[] args) throws InterruptedException {        
        Jedis jedis = JedisUtils.getJedis();        
        // 30s 后执行        
        long delayTime = Instant.now().plusSeconds(30).getEpochSecond();       
        jedis.zadd(_KEY, delayTime, "order_1");        
        // 继续添加测试数据        
       jedis.zadd(_KEY, Instant.now().plusSeconds(2).getEpochSecond(), "order_2");       
      jedis.zadd(_KEY, Instant.now().plusSeconds(2).getEpochSecond(), "order_3");        
      jedis.zadd(_KEY, Instant.now().plusSeconds(7).getEpochSecond(), "order_4");        
     jedis.zadd(_KEY, Instant.now().plusSeconds(10).getEpochSecond(), "order_5");        
        // 开启定时任务队列        
        doDelayQueue(jedis);    
    }    
    /**     
    * 定时任务队列消费     
    * @param jedis Redis 客户端     
    */    
    public static void doDelayQueue(Jedis jedis) throws InterruptedException {        
        while (true) {            
            // 当前时间            
            Instant nowInstant = Instant.now();            
            long lastSecond = nowInstant.plusSeconds(-1).getEpochSecond(); 
            // 上一秒时间            
            long nowSecond = nowInstant.getEpochSecond();            
            // 查询当前时间的所有任务            
            Set data = jedis.zrangeByScore(_KEY, lastSecond, nowSecond);            
            for (String item : data) {                
            // 消费任务                
            System.out.println("消费:" + item);            
        }            
        // 删除已经执行的任务            
        jedis.zremrangeByScore(_KEY, lastSecond, nowSecond);            
        Thread.sleep(1000); // 每秒查询一次        
        }    
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值