定时任务

This commit is contained in:
lhx
2025-09-27 11:42:26 +08:00
parent 173935014e
commit 345ee50a7b
5 changed files with 54 additions and 7 deletions

View File

@@ -4,6 +4,8 @@ from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
import logging
from ..core.config import settings
from ..core.database import SessionLocal
from ..models.account import Account
# 配置日志
logging.basicConfig(level=logging.INFO)
@@ -51,12 +53,35 @@ class TaskScheduler:
self.scheduler.start()
logger.info("定时任务调度器已启动")
# 启动时自动添加系统定时任务
self._setup_system_tasks()
def shutdown(self):
"""关闭调度器"""
if self.scheduler.running:
self.scheduler.shutdown()
logger.info("定时任务调度器已关闭")
def _setup_system_tasks(self):
"""设置系统定时任务"""
try:
# 检查是否已存在每日重置任务
existing_job = self.scheduler.get_job("daily_reset_today_updated")
if not existing_job:
# 添加每天午夜12点重置today_updated字段的任务
self.scheduler.add_job(
reset_today_updated_task,
'cron',
id='daily_reset_today_updated',
hour=0,
minute=0,
second=0,
name='每日重置账号更新状态'
)
logger.info("系统定时任务:每日重置账号更新状态已添加")
except Exception as e:
logger.error(f"设置系统定时任务失败: {e}")
def add_cron_job(self, func, job_id: str, **kwargs):
"""添加cron定时任务"""
return self.scheduler.add_job(func, 'cron', id=job_id, **kwargs)
@@ -110,6 +135,27 @@ class TaskScheduler:
# 全局调度器实例
task_scheduler = TaskScheduler()
# 系统定时任务函数
def reset_today_updated_task():
"""每日重置账号today_updated字段为0的任务"""
db = SessionLocal()
try:
logger.info("开始执行每日重置账号更新状态任务")
# 更新所有账号的today_updated字段为0
updated_count = db.query(Account).update({Account.today_updated: 0})
db.commit()
logger.info(f"每日重置任务完成,已重置 {updated_count} 个账号的today_updated字段")
return f"成功重置 {updated_count} 个账号的更新状态"
except Exception as e:
db.rollback()
logger.error(f"每日重置任务执行失败: {e}")
raise e
finally:
db.close()
# 示例定时任务函数
def example_task():
"""示例定时任务"""