如何在 asyncio 中安排任务以使其在特定日期运行? [英] How to schedule a task in asyncio so it runs at a certain date?

查看:51
本文介绍了如何在 asyncio 中安排任务以使其在特定日期运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序应该 24/7 全天候运行,我希望能够在某个时间/日期运行一些任务.

My program is supposed to run 24/7 and i want to be able to run some tasks at a certain hour/date.

我已经尝试使用 aiocron 但它只支持调度函数(不支持协程)并且我读过这不是一个很好的图书馆.我的程序是这样构建的,所以我想要安排的大部分任务都是在协程中构建的.

I have already tried to work with aiocron but it only supports scheduling functions (not coroutines) and i have read that is not a really good library. My program is built so most if not all the tasks that i would want to schedule are built in coroutines.

有没有其他库可以实现这种任务调度?

Is there any other library that allows for such kind of task scheduling?

或者如果没有,有什么方法可以扭曲协程,使它们运行正常的功能?

Or if not, any way of warping coroutines so they run of a normal function?

推荐答案

我已经尝试过使用 aiocron 但它只支持调度函数(不支持协程)

I have already tried to work with aiocron but it only supports scheduling functions (not coroutines)

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

According to the examples at the link you provided, that does not appear to be the case. The functions decorated with @asyncio.coroutine are equivalent to coroutines defined with async def, and you can use them interchangeably.

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

However, if you want to avoid aiocron, it is straightforward to use asyncio.sleep to postpone running a coroutine until an arbitrary point in time. For example:

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 必须解决这个限制.这个答案的原始版本是这样定义的:


Note: Python versions before 3.8 didn't support sleeping intervals longer than 24 days, so wait_until had to work around the limitation. The original version of this answer defined it like this:

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.

The limitation was removed in Python 3.8 and the fix was backported to 3.6.7 and 3.7.1.

这篇关于如何在 asyncio 中安排任务以使其在特定日期运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆