How To Schedule A Task In Asyncio So It Runs At A Certain Date?
Solution 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 straightforward to use asyncio.sleep
to postpone running a coroutine until an arbitrary point in time. For example:
import asyncio, datetime
asyncdefwait_until(dt):
# sleep until the specified datetime
now = datetime.datetime.now()
await asyncio.sleep((dt - now).total_seconds())
asyncdefrun_at(dt, coro):
await wait_until(dt)
returnawait 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()
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:
asyncdefwait_until(dt):
# sleep until the specified datetimewhileTrue:
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 timeawait asyncio.sleep(86400)
await asyncio.sleep(remaining)
The limitation was removed in Python 3.8 and the fix was backported to 3.6.7 and 3.7.1.
Post a Comment for "How To Schedule A Task In Asyncio So It Runs At A Certain Date?"