【发布时间】:2021-01-25 23:01:30
【问题描述】:
我想要一个异步调度器来执行“动作”,它满足某些属性:
- 操作是一次性的,并按确切的时间戳安排。
- 操作应按
严格顺序顺序执行,即调度程序在前一个操作完成执行之前无法启动下一个操作。 - 在动作执行之间,当调度器等待下一个时间戳时,调度器必须处于
asyncio.sleep()的状态,才能让其他协程轮到自己。 - 当安排了新动作时,调度程序应立即重新调整其等待时间,以便调度程序始终等待尽可能快的动作。
- 当未安排任何操作时,计划程序应处于
asyncio.sleep()的永久状态,直到添加新操作。
我的尝试:
import asyncio
import time
class Action:
def __init__(self, timestamp):
self.timestamp = timestamp
async def do(self):
print("Doing action...")
class Scheduler:
def __init__(self):
self._actions = []
self._sleep_future = None
def add(self, action):
self._actions.append(action)
self._actions.sort(key=lambda x: x.timestamp)
if self._sleep_future:
self._sleep_future.cancel()
def pop(self):
return self._actions.pop(0)
async def start(self):
asyncio.create_task(self.loop())
async def loop(self):
while True:
now = time.time()
while self._actions:
action = self._actions[0]
if action.timestamp <= now:
action = self.pop()
await action.do()
else:
break
self._sleep_future = asyncio.ensure_future(
asyncio.sleep(self._actions[0].timestamp - now)
)
try:
await self._sleep_future
except asyncio.CancelledError:
continue
finally:
self._sleep_future = None
这个实现不可靠,没有考虑到我所寻求的条件(5)!
你能给我推荐点什么吗?
【问题讨论】:
标签: python asynchronous scheduled-tasks python-asyncio