定时任务
This commit is contained in:
@@ -4,7 +4,7 @@ from ..schemas.task import (
|
|||||||
JobResponse, AddCronJobRequest, AddIntervalJobRequest,
|
JobResponse, AddCronJobRequest, AddIntervalJobRequest,
|
||||||
AddDateJobRequest, TaskResponse
|
AddDateJobRequest, TaskResponse
|
||||||
)
|
)
|
||||||
from ..utils.scheduler import task_scheduler, example_task, database_cleanup_task
|
from ..utils.scheduler import task_scheduler, example_task, database_cleanup_task, reset_today_updated_task
|
||||||
|
|
||||||
router = APIRouter(prefix="/tasks", tags=["定时任务管理"])
|
router = APIRouter(prefix="/tasks", tags=["定时任务管理"])
|
||||||
|
|
||||||
@@ -12,6 +12,7 @@ router = APIRouter(prefix="/tasks", tags=["定时任务管理"])
|
|||||||
AVAILABLE_FUNCTIONS = {
|
AVAILABLE_FUNCTIONS = {
|
||||||
"example_task": example_task,
|
"example_task": example_task,
|
||||||
"database_cleanup_task": database_cleanup_task,
|
"database_cleanup_task": database_cleanup_task,
|
||||||
|
"reset_today_updated_task": reset_today_updated_task,
|
||||||
}
|
}
|
||||||
|
|
||||||
@router.post("/cron", response_model=TaskResponse)
|
@router.post("/cron", response_model=TaskResponse)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from pydantic import BaseModel
|
from pydantic import BaseModel, Field
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
@@ -20,12 +20,13 @@ class AccountUpdate(BaseModel):
|
|||||||
project_name: Optional[str] = None
|
project_name: Optional[str] = None
|
||||||
|
|
||||||
class AccountResponse(AccountBase):
|
class AccountResponse(AccountBase):
|
||||||
id: int
|
account_id: int = Field(alias="id")
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
updated_at: datetime
|
updated_at: datetime
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
from_attributes = True
|
from_attributes = True
|
||||||
|
populate_by_name = True
|
||||||
|
|
||||||
class AccountListRequest(BaseModel):
|
class AccountListRequest(BaseModel):
|
||||||
skip: Optional[int] = 0
|
skip: Optional[int] = 0
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ class AccountService:
|
|||||||
setattr(db_account, field, value)
|
setattr(db_account, field, value)
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(db_account)
|
db.refresh(db_account)
|
||||||
|
|
||||||
return db_account
|
return db_account
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
|
|||||||
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
|
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
|
||||||
import logging
|
import logging
|
||||||
from ..core.config import settings
|
from ..core.config import settings
|
||||||
|
from ..core.database import SessionLocal
|
||||||
|
from ..models.account import Account
|
||||||
|
|
||||||
# 配置日志
|
# 配置日志
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
@@ -51,12 +53,35 @@ class TaskScheduler:
|
|||||||
self.scheduler.start()
|
self.scheduler.start()
|
||||||
logger.info("定时任务调度器已启动")
|
logger.info("定时任务调度器已启动")
|
||||||
|
|
||||||
|
# 启动时自动添加系统定时任务
|
||||||
|
self._setup_system_tasks()
|
||||||
|
|
||||||
def shutdown(self):
|
def shutdown(self):
|
||||||
"""关闭调度器"""
|
"""关闭调度器"""
|
||||||
if self.scheduler.running:
|
if self.scheduler.running:
|
||||||
self.scheduler.shutdown()
|
self.scheduler.shutdown()
|
||||||
logger.info("定时任务调度器已关闭")
|
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):
|
def add_cron_job(self, func, job_id: str, **kwargs):
|
||||||
"""添加cron定时任务"""
|
"""添加cron定时任务"""
|
||||||
return self.scheduler.add_job(func, 'cron', id=job_id, **kwargs)
|
return self.scheduler.add_job(func, 'cron', id=job_id, **kwargs)
|
||||||
@@ -110,6 +135,27 @@ class TaskScheduler:
|
|||||||
# 全局调度器实例
|
# 全局调度器实例
|
||||||
task_scheduler = 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():
|
def example_task():
|
||||||
"""示例定时任务"""
|
"""示例定时任务"""
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ name = "tielu-railway-management"
|
|||||||
version = "1.0.0"
|
version = "1.0.0"
|
||||||
description = "Railway Project Management System"
|
description = "Railway Project Management System"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.11"
|
requires-python = ">=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"fastapi>=0.104.1",
|
"fastapi>=0.104.1",
|
||||||
"uvicorn>=0.24.0",
|
"uvicorn>=0.24.0",
|
||||||
@@ -19,8 +19,6 @@ dependencies = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[tool.uv.index]
|
[tool.uv.index]
|
||||||
urls = [
|
url = "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple"
|
||||||
"https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple"
|
|
||||||
]
|
|
||||||
python-install-mirror = "https://mirror.nju.edu.cn/github-release/indygreg/python-build-standalone"
|
python-install-mirror = "https://mirror.nju.edu.cn/github-release/indygreg/python-build-standalone"
|
||||||
default = true
|
default = true
|
||||||
|
|||||||
Reference in New Issue
Block a user