How to schedule a task in asyncio so it runs at a certain date?

萝らか妹 提交于 2020-01-11 03:07:08

问题


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

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?


回答1:


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

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.

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

import asyncio, datetime

async def wait_for(dt):
    # sleep until the specified datetime
    while True:
        now = datetime.datetime.now()
        remaining = (dt - now).total_seconds()
        if remaining < 86400:
            break
        # asyncio.sleep doesn't like long sleeps, so don't sleep more
        # than a day at a time
        await asyncio.sleep(86400)
    await asyncio.sleep(remaining)

async def run_at(dt, coro):
    await wait_for(dt)
    return await coro

Example usage:

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()


来源:https://stackoverflow.com/questions/51292027/how-to-schedule-a-task-in-asyncio-so-it-runs-at-a-certain-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!