您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

我已经尝试过使用aiocron,但它仅支持调度功能不支持协程)

根据您提供的链接上的示例,情况似乎并非如此。装饰的功能@asyncio.coroutine等同于用定义的协程async def,您可以互换使用它们。

但是,如果要避免使用Aiocron,可以直接将asyncio.sleep协程推迟运行到任意时间点。例如:

import asyncio, datetime

async 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 written
loop.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。

其他 2022/1/1 18:34:16 有515人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶