首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在asyncio中调度一个任务,让它在某个日期运行?

如何在asyncio中调度一个任务,让它在某个日期运行?
EN

Stack Overflow用户
提问于 2018-07-12 02:23:43
回答 1查看 13.1K关注 0票数 15

我的程序应该是全天候运行的,我希望能够在特定的时间/日期运行一些任务。

我已经尝试过使用aiocron,但它只支持调度函数(不支持协程),而且我知道它不是一个很好的库。我的程序是这样构建的,所以我想调度的大部分任务都是在协程中构建的。

有没有其他的库允许这样的任务调度?

或者,如果不是,有没有办法修改协程,使它们运行正常函数?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-12 05:36:55

我已经尝试过使用

,但它只支持调度功能(不支持协程)

根据您提供的link中的示例,情况似乎并非如此。用@asyncio.coroutine修饰的函数等同于用async def定义的协程,并且可以互换使用。

但是,如果您想要避免aiocron,那么使用asyncio.sleep将协程的运行推迟到任意时间点是很简单的。例如:

代码语言:javascript
复制
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

示例用法:

代码语言:javascript
复制
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()

注意:Python3.8之前的版本不支持睡眠间隔超过24天,因此wait_until必须解决这个限制。这个答案的原始版本是这样定义的:

代码语言:javascript
复制
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)

Python3.8中的限制是removed,修复程序被反向移植到3.6.7和3.7.1。

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51292027

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档