Python APScheduler - AsyncIOScheduler 如何工作?

标签 python apscheduler

我很难理解 AsyncIOScheduler有效,它是如何非阻塞的?
如果我的工作正在执行阻塞函数,AsyncIOScheduler 是否会出现?被堵?
如果我使用 AsyncIOScheduler 呢?与 ThreadPoolExecutor ?这是如何运作的?我可以等待作业执行吗?

最佳答案

使用一些互联网资源,我发现了一些有用的事实。希望它会帮助你。
一个典型的 APScheduler 实例包含数十个执行常规 Python 函数的作业。 APScheduler 实例可以调度的作业数量没有限制;它只取决于机器的实际负载。默认情况下,APScheduler 将所有作业存储在内存中。如果您希望您的作业在进程重新启动后继续存在并从上次触发时继续触发,您可以将这些作业存储在数据库中,例如任何 RDBMS、Redis、MongoDB 等。
根据您的应用程序的运行方式,它可以作为线程、异步任务或其他方式运行。初始化时,除非您将 Python 函数添加为作业,否则 APScheduler 不会执行任何操作。添加所有作业后,您需要“启动”调度程序。有关如何使用 APScheduler 的简单示例,这里是一段有效的代码。

from urllib.request import urlopen
from apscheduler.schedulers.blocking import BlockingScheduler

scheduler = BlockingScheduler()

@scheduler.scheduled_job("interval", seconds=10)
def keep_warm():
    urlopen("https://enqueuezero.com", timeout=10)
    
scheduler.start()
这确保每 10 秒请求一个 URL。该程序作为阻塞进程运行。如果您希望它们与您的应用程序共存,您可以考虑使用 BackgroundScheduler , AsyncIOScheduler , 等等。
这里是 BackgroundScheduler 的一些代码片段.
from datetime import datetime
import time
import os

from apscheduler.schedulers.background import BackgroundScheduler


def tick():
    print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    scheduler = BackgroundScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    try:
        # This is here to simulate application activity (which keeps the main thread alive).
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        # Not strictly necessary if daemonic mode is enabled but should be done if possible
        scheduler.shutdown()
下面的代码将演示如何使用 asyncio兼容的调度程序来调度以 3 秒为间隔执行的作业。
import asyncio
import os
from datetime import datetime

from apscheduler.schedulers.asyncio import AsyncIOScheduler


def tick():
    print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    scheduler = AsyncIOScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    # Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
    try:
        asyncio.get_event_loop().run_forever()
    except (KeyboardInterrupt, SystemExit):
        pass
您可以使用此 link 获得更多有关 apscheduler 的示例。 !

关于Python APScheduler - AsyncIOScheduler 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63001954/

相关文章:

python - kwargs/args 错误。将参数传递给 apscheduler 处理函数

python - 如何在 Python Flask 框架中运行循环任务?

python - 如何使用 APScheduler 设置小时范围和分钟间隔

python - 将表示为 numpy ndarray 的彩色图像更改为灰度

python - GridSearchCV 的结果作为表格

python - 从列表的列表中删除重复的列表项

python - FastAPI:带有点的表单数据名称

python - 如何设置 Python apscheduler 在每天 9、11、14、17、18 时钟运行作业

flask - 如何使用postman通过flask apscheduler api添加作业

python - Sklearn SGDClassifier 部分拟合