FastAPI中如何正确使用ApScheduler?

jia*_*nyi 6 python-3.x apscheduler fastapi uvicorn

from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nimport uvicorn\nimport time\nfrom loguru import logger\nfrom apscheduler.schedulers.background import BackgroundScheduler\n\napp = FastAPI()\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=["*"],\n    allow_credentials=True,\n    allow_methods=["*"],\n    allow_headers=["*"],\n)\n\ntest_list = ["1"]*10\n\ndef check_list_len():\n    global test_list\n    while True:\n        time.sleep(5)\n        logger.info(f"check_list_len\xef\xbc\x9a{len(test_list)}")\n\n@app.on_event('startup')\ndef init_data():\n    scheduler = BackgroundScheduler()\n    scheduler.add_job(check_list_len, 'cron', second='*/5')\n    scheduler.start()\n\n@app.get("/pop")\nasync def list_pop():\n    global test_list\n    test_list.pop(1)\n    logger.info(f"current_list_len:{len(test_list)}")\n\n\nif __name__ == '__main__':\n    uvicorn.run(app="main3:app", host="0.0.0.0", port=80, reload=False, debug=False)\n
Run Code Online (Sandbox Code Playgroud)\n

上面是我的代码,我想通过get请求取出一个列表元素,并设置一个周期性任务不断检查列表中的元素数量,但是当我运行时,总是出现以下错误:

\n
Execution of job "check_list_len (trigger: cron[second='*/5'], next run at: 2021-11-25 09:48:50 CST)" skipped: maximum number of running instances reached (1)\n2021-11-25 09:48:50.016 | INFO     | main3:check_list_len:23 - check_list_len\xef\xbc\x9a10\nExecution of job "check_list_len (trigger: cron[second='*/5'], next run at: 2021-11-25 09:48:55 CST)" skipped: maximum number of running instances reached (1)\n2021-11-25 09:48:55.018 | INFO     | main3:check_list_len:23 - check_list_len\xef\xbc\x9a10\nINFO:     127.0.0.1:55961 - "GET /pop HTTP/1.1" 200 OK\n2021-11-25 09:48:57.098 | INFO     | main3:list_pop:35 - current_list_len:9\nExecution of job "check_list_len (trigger: cron[second='*/5'], next run at: 2021-11-25 09:49:00 CST)" skipped: maximum number of running instances reached (1)\n2021-11-25 09:49:00.022 | INFO     | main3:check_list_len:23 - check_list_len\xef\xbc\x9a9\n
Run Code Online (Sandbox Code Playgroud)\n

看起来我启动了两项计划任务,只有一项成功,但我只启动了一项任务。我该如何避免这种情况

\n

Mat*_*ndh 6

您正在得到您所要求的行为。您已将 apscheduler 配置为check_list_len每五秒运行一次,但您还设置了该函数运行时不会终止 - 只是在无限循环中休眠五秒。该函数永远不会终止,因此apscheduler不会再次运行它 - 因为它还没有完成。

\n

使用时删除实用程序函数内的无限循环apscheduler- 它会每五秒为您调用该函数:

\n
def check_list_len():\n    global test_list  # you really don't need this either, since you're not reassigning the variable\n    logger.info(f"check_list_len\xef\xbc\x9a{len(test_list)}")\n
Run Code Online (Sandbox Code Playgroud)\n