优化定时任务管理:实现应用启动时自动加载启用的定时任务功能
This commit is contained in:
parent
a4b53a2c8b
commit
30a9056751
21
main.py
21
main.py
@ -96,6 +96,27 @@ app = FastAPI(
|
||||
version="0.1.0",
|
||||
)
|
||||
|
||||
# 在应用启动时加载所有启用的定时任务
|
||||
@app.on_event("startup")
|
||||
async def load_scheduled_tasks():
|
||||
"""系统启动时,自动将enabled为true的任务加入调度器"""
|
||||
try:
|
||||
db = SessionLocal()
|
||||
enabled_tasks = db.query(ScheduledTask).filter(ScheduledTask.enabled == True).all()
|
||||
|
||||
if enabled_tasks:
|
||||
logger.info(f"正在加载 {len(enabled_tasks)} 个启用的定时任务...")
|
||||
for task in enabled_tasks:
|
||||
add_job_to_scheduler(task)
|
||||
logger.info(f"已加载定时任务: {task.name} (ID: {task.id}, Cron: {task.cron_expression})")
|
||||
else:
|
||||
logger.info("没有找到启用的定时任务")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"加载定时任务时出错: {str(e)}", exc_info=True)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
# 存储爬虫任务状态
|
||||
spider_tasks = {}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user