延时队列
https://www.jianshu.com/p/a663e52e6488
import queue import datetime import threading import functools class DelayedTask(object): def __init__(self, plan_time, job_func): self.plan_time = plan_time # 单位: datetime self.job_func = job_func # 执行的方法,此处是简易版 def total_seconds(td): return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 6 class DelayQueue(queue.PriorityQueue): def __init__(self, maxsize=100): self.can_done = threading.Condition() super(DelayQueue, self).__init__() def put_task(self, task): self.put((task.plan_time, task)) def get_task(self): self.can_done.acquire() try: task = self._peek() delta = total_seconds(task.plan_time - datetime.datetime.now()) while delta > 0: self.can_done.wait(delta) # 这里会挂起,挂delta秒 task = self._peek() delta = total_seconds(task.plan_time - datetime.datetime.now()) item = self.get() self.can_done.notify_all() return item[1] finally: self.can_done.release() def _peek(self): self.not_empty.acquire() try: while not self._qsize(): self.not_empty.wait() return self.queue[0][1] finally: self.not_empty.release() def hello_world(name): print("%s say hello world" %(name)) if __name__ == '__main__': task1_hello_world = functools.partial(hello_world, name="dsgdtc5秒") task2_hello_world = functools.partial(hello_world, name="dsgdtc1秒") task1 = DelayedTask(plan_time=datetime.datetime.now() + datetime.timedelta(seconds=5), job_func=task1_hello_world) task2 = DelayedTask(plan_time=datetime.datetime.now() + datetime.timedelta(seconds=1), job_func=task2_hello_world) delay_queue = DelayQueue() # 5秒的先入队列 delay_queue.put_task(task1) res = delay_queue.get_task() res.job_func() # 1秒的后入队列,1秒任务需要等5秒的完成后才执行。 # 可以根据业务场景做多个优先级队列解决,比如做3个队列 # 分别存放1秒钟延迟任务;5秒钟延迟任务;10秒钟延迟任务。 # 任意时间的解决方式。 # 暂定利用redis的zset结构,(taskid, task, task_timestamp)用task_timestamp做score存入redis中,taskid是key # taskid和task再放到一个bucket中 # 然后加个轮询,只轮询score大于当前时间的key,拿到key后去bucket中找对应task delay_queue.put_task(task2) res = delay_queue.get_task() print(res) res.job_func()
https://blog.csdn.net/weixin_39900286/article/details/111750070
https://www.cnblogs.com/hellojesson/p/11547014.html
import sched,time def func(a): print(time.time(),"Hello Sched!",a) print(time.time()) s = sched.scheduler(time.time,time.sleep) # 2为延后时间,1为优先级,func为函数名,("test1",)为函数参数 s.enter(1,1,func,("test1",)) s.enter(2,3,func,("test2",)) s.enter(2,0,func,("test3",)) s.enter(1,1,func,("test4",)) s.run() print(time.time())
import threading,time def func(a): print(time.time(),"Hello Sched!",a) print(time.time()) s = threading.Timer(2,func,("test",)) s.start() print(time.time())
2022-04-01 22:00:54
本文来自博客园,作者:CodeYaSuo,转载请注明原文链接:https://www.cnblogs.com/hany-postq473111315/p/16089381.html