我的程序应该是全天候运行的,我希望能够在特定的时间/日期运行一些任务。
我已经尝试过使用aiocron,但它只支持调度函数(不支持协程),而且我知道它不是一个很好的库。我的程序是这样构建的,所以我想调度的大部分任务都是在协程中构建的。
有没有其他的库允许这样的任务调度?
或者,如果不是,有没有办法修改协程,使它们运行正常函数?
发布于 2018-07-12 05:36:55
我已经尝试过使用
,但它只支持调度功能(不支持协程)
根据您提供的link中的示例,情况似乎并非如此。用@asyncio.coroutine修饰的函数等同于用async def定义的协程,并且可以互换使用。
但是,如果您想要避免aiocron,那么使用asyncio.sleep将协程的运行推迟到任意时间点是很简单的。例如:
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()注意:Python3.8之前的版本不支持睡眠间隔超过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)Python3.8中的限制是removed,修复程序被反向移植到3.6.7和3.7.1。
https://stackoverflow.com/questions/51292027
复制相似问题