如何安排任务在asyncio中使其在特定日期运行?

如何安排任务在asyncio中使其在特定日期运行?,第1张

如何安排任务在asyncio中使其在特定日期运行

我已经尝试过使用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。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5632125.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存