栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何安排任务在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。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/626240.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号