我已经尝试过使用aiocron,但它仅支持调度功能(不支持协程)
根据您提供的链接上的示例,情况似乎并非如此。装饰的功能
@asyncio.coroutine等同于用定义的协程
asyncdef,您可以互换使用它们。
但是,如果要避免使用Aiocron,可以直接将
asyncio.sleep协程推迟运行到任意时间点。例如:
import asyncio, datetimeasync def wait_until(dt): # sleep until the specified datetime now = datetime.datetime.now() await asyncio.sleep((dt - now).total_seconds())async def run_at(dt, coro): await wait_until(dt) return await coro
用法示例:
async def hello(): print('hello')loop = asyncio.get_event_loop()# print hello ten years after this answer was writtenloop.create_task(run_at(datetime.datetime(2028, 7, 11, 23, 36), hello()))loop.run_forever()
注意:3.8之前的Python版本不支持超过24天的睡眠间隔,因此
wait_until必须解决该限制。该答案的原始版本定义如下:
async def wait_until(dt): # sleep until the specified datetime while True: now = datetime.datetime.now() remaining = (dt - now).total_seconds() if remaining < 86400: break # pre-3.7.1 asyncio doesn't like long sleeps, so don't sleep # for more than one day at a time await asyncio.sleep(86400) await asyncio.sleep(remaining)
该限制已在Python
3.8中删除,并且修复程序已反向移植到3.6.7和3.7.1。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)