赞
踩
# redis 的zset是有序集合,可以通过分数进行排序
# 将分数设置成任务执行时间
# 通过 ZRANGEBYSCORE key min max 获取任务时间小于当前时间的任务
# 通过 ZREMRANGEBYRANK key 0 0 来移除 执行完的任务
# ZRANGEBYSCORE,ZREMRANGEBYRANK 都是按照分数从小到大排
redisManger
class RedisManger { private $redis; private $config = [ 'host' => '127.0.0.1', 'port' => 6379 ]; public function __construct($redisConfig = []) { $redis = new Redis(); $config = array_merge($this->config, $redisConfig); $redis->connect($config['host'], $config['port']); $this->redis = $redis; } public function zAdd($key, $score, $value) { $this->redis->zAdd($key, $score, $value); } public function zGet($key, $max) { return $this->redis->zRangeByScore($key, 0, $max); } public function zRemove($key) { return $this->redis->zRemRangeByRank($key, 0, 0); } }
consumer
# 引入 redisManger require "./redis.php"; $redis = new RedisManger(); $key = 'test'; while (true) { $data = $redis->zGet($key, time()); if ($data) { foreach ($data as $value) { # 执行逻辑 echo $value . PHP_EOL; # 移除 $redis->zRemove($key); } } sleep(1); }
producer
# 引入 redisManger
require "./redis.php";
$redis = new RedisManger();
$time = time();
$redis->zAdd('test', time() + 50, "this is after 50 seconds");
$redis->zAdd('test', time() + 30, "this is after 30 seconds");
$redis->zAdd('test', time() + 40, "this is after 40 seconds");
php ./consumer.php
php ./producer.php
xieruixiang@xieruixiangdeMacBook-Pro bin % php ./consumer.php
this is after 30 seconds
this is after 40 seconds
this is after 50 seconds
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。