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

How to use redis to implement countdown tasks

王林
Release: 2023-05-26 21:58:04
forward
1231 people have browsed it

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)
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template