Home  >  Article  >  Database  >  How to use redis to implement countdown tasks

How to use redis to implement countdown tasks

WBOY
WBOYforward
2023-05-30 23:55:051598browse

Examples are as follows:

import redis
import time

def event_handler(msg):  
    '''
    监听到任何key过期后,得到的消息如下
    msg ={'type': 'pmessage', #返回值类型
    'pattern': '__keyevent@2__:expired', #来源
     'channel': '__keyevent@2__:expired', # 实际的Channel
      'data': 'mykey' # key名称
      }
    可以根据您要监控的key进行业务判断或触发其他事件
    if msg['data']=='mykey':
        do....
    elif msg['data']=='yourkey':
        do ----
    '''
    print(msg)
 
    
redis_conn = redis.Redis(host='host', port='6379', db=2, password='test.123.com', decode_responses=True)
#设置过期时间2秒
redis_conn.set('mykey', 'asjdhkjashdkjahdskjahsd', ex=2)
# 订阅消息
pubsub =redis_conn.pubsub()
# 订阅key过期事件
# __keyevent@2__:expired : __keyevent@{db}__:事件
pubsub.psubscribe(**{'__keyevent@2__:expired': event_handler})
while True:  
    message = pubsub.get_message()
    if message:
        # redis_conn.set('mykey', 'asjdhkjashdkjahdskjahsd', ex=10)
        print('wqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwq')
    else:
        time.sleep(0.01)

The above is the detailed content of How to use redis to implement countdown tasks. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete