Lai*_*kar 5 python scheduled-tasks python-asyncio
我的程序应该运行24/7,我希望能够在某个小时/日期运行某些任务。
我已经尝试使用aiocron,但它仅支持调度功能(不支持协程),并且我读到它并不是一个很好的库。我的程序是构建的,因此我要调度的大多数(如果不是全部)任务都是在协程中构建的。
还有其他库可以进行此类任务调度吗?
否则,是否有任何使协程变形的方法,以使它们运行正常?
use*_*342 15
我已经尝试过使用 aiocron 但它只支持调度函数(不支持协程)
根据您提供的链接中的示例,情况似乎并非如此。修饰的函数@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
Run Code Online (Sandbox Code Playgroud)
用法示例:
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()
Run Code Online (Sandbox Code Playgroud)
注意:3.8 之前的 Python 版本不支持超过 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)
Run Code Online (Sandbox Code Playgroud)
该限制在 Python 3.8 中被移除,并且修复被反向移植到 3.6.7 和 3.7.1。
| 归档时间: |
|
| 查看次数: |
2839 次 |
| 最近记录: |