场景
做过工单或订单项目的人大概都用过定时器。一般来说,项目里订单模块可能会涉及到定时任务执行。比如说:
- 用户下订单后,需要在10分钟内完成支付,否则订单关闭;
- 用户在完成订单后,如果没有评论,过一星期,系统自动评论,并完结。
我曾经做过一个私有云系统,重启或重装的执行是有时间限制的,如果超时会触发报警操作
有一种比较笨的方法就是在任务下发中加入过期时间,后台启动一个定时线程,每隔一段时间遍历一次服务器状态。这种方法比较影响系统性能。
后来通过调研发现了Redis有一个定时器的功能,通过expire设置key的过期时间,使用发布订阅模式,可以接收到key的过期提醒,当key过期时,再执行报警操作,就可以了。
启用键空间通知
默认情况下,禁用键空间事件通知。我们可以在redis.conf或redis-cli中启用它们,如下所示:
./redis-cli config set notify-keyspace-events KEAOK
Python调用
import timefrom redis import StrictRedisredis = StrictRedis(host='localhost', port=6379, password='11111', decode_responses=True)pubsub = redis.pubsub()# 回调逻辑写这里def event_handler(msg):print('Handler', msg)pubsub.psubscribe(**{'__keyspace@0__:*': event_handler})print('Starting message loop')while True:message = pubsub.get_message()if message:print(message)else:time.sleep(0.01)Starting message loop{'pattern': None, 'channel': b'__keyspace@0__:*', 'data': 1, 'type': 'psubscribe'}Handler {'pattern': b'__keyspace@0__:*', 'channel': b'__keyspace@0__:mykey', 'data': b'set', 'type': 'pmessage'}
