初始化
This commit is contained in:
3
app/utils/__init__.py
Normal file
3
app/utils/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from .scheduler import task_scheduler, example_task, database_cleanup_task
|
||||
|
||||
__all__ = ["task_scheduler", "example_task", "database_cleanup_task"]
|
||||
BIN
app/utils/__pycache__/__init__.cpython-312.pyc
Normal file
BIN
app/utils/__pycache__/__init__.cpython-312.pyc
Normal file
Binary file not shown.
BIN
app/utils/__pycache__/scheduler.cpython-312.pyc
Normal file
BIN
app/utils/__pycache__/scheduler.cpython-312.pyc
Normal file
Binary file not shown.
124
app/utils/scheduler.py
Normal file
124
app/utils/scheduler.py
Normal file
@@ -0,0 +1,124 @@
|
||||
from apscheduler.schedulers.background import BackgroundScheduler
|
||||
from apscheduler.executors.pool import ThreadPoolExecutor
|
||||
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
|
||||
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
|
||||
import logging
|
||||
from ..core.config import settings
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class TaskScheduler:
|
||||
def __init__(self):
|
||||
# 配置作业存储
|
||||
jobstores = {
|
||||
'default': SQLAlchemyJobStore(url=settings.DATABASE_URL)
|
||||
}
|
||||
|
||||
# 配置执行器
|
||||
executors = {
|
||||
'default': ThreadPoolExecutor(20)
|
||||
}
|
||||
|
||||
# 作业默认配置
|
||||
job_defaults = {
|
||||
'coalesce': False,
|
||||
'max_instances': 3
|
||||
}
|
||||
|
||||
# 创建调度器
|
||||
self.scheduler = BackgroundScheduler(
|
||||
jobstores=jobstores,
|
||||
executors=executors,
|
||||
job_defaults=job_defaults,
|
||||
timezone='Asia/Shanghai'
|
||||
)
|
||||
|
||||
# 添加事件监听器
|
||||
self.scheduler.add_listener(self._job_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
|
||||
|
||||
def _job_listener(self, event):
|
||||
"""作业执行监听器"""
|
||||
if event.exception:
|
||||
logger.error(f"Job {event.job_id} crashed: {event.exception}")
|
||||
else:
|
||||
logger.info(f"Job {event.job_id} executed successfully")
|
||||
|
||||
def start(self):
|
||||
"""启动调度器"""
|
||||
if not self.scheduler.running:
|
||||
self.scheduler.start()
|
||||
logger.info("定时任务调度器已启动")
|
||||
|
||||
def shutdown(self):
|
||||
"""关闭调度器"""
|
||||
if self.scheduler.running:
|
||||
self.scheduler.shutdown()
|
||||
logger.info("定时任务调度器已关闭")
|
||||
|
||||
def add_cron_job(self, func, job_id: str, **kwargs):
|
||||
"""添加cron定时任务"""
|
||||
return self.scheduler.add_job(func, 'cron', id=job_id, **kwargs)
|
||||
|
||||
def add_interval_job(self, func, job_id: str, **kwargs):
|
||||
"""添加间隔执行任务"""
|
||||
return self.scheduler.add_job(func, 'interval', id=job_id, **kwargs)
|
||||
|
||||
def add_date_job(self, func, job_id: str, **kwargs):
|
||||
"""添加指定时间执行任务"""
|
||||
return self.scheduler.add_job(func, 'date', id=job_id, **kwargs)
|
||||
|
||||
def remove_job(self, job_id: str):
|
||||
"""移除任务"""
|
||||
try:
|
||||
self.scheduler.remove_job(job_id)
|
||||
logger.info(f"任务 {job_id} 已移除")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"移除任务失败: {e}")
|
||||
return False
|
||||
|
||||
def get_job(self, job_id: str):
|
||||
"""获取任务"""
|
||||
return self.scheduler.get_job(job_id)
|
||||
|
||||
def get_jobs(self):
|
||||
"""获取所有任务"""
|
||||
return self.scheduler.get_jobs()
|
||||
|
||||
def pause_job(self, job_id: str):
|
||||
"""暂停任务"""
|
||||
try:
|
||||
self.scheduler.pause_job(job_id)
|
||||
logger.info(f"任务 {job_id} 已暂停")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"暂停任务失败: {e}")
|
||||
return False
|
||||
|
||||
def resume_job(self, job_id: str):
|
||||
"""恢复任务"""
|
||||
try:
|
||||
self.scheduler.resume_job(job_id)
|
||||
logger.info(f"任务 {job_id} 已恢复")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"恢复任务失败: {e}")
|
||||
return False
|
||||
|
||||
# 全局调度器实例
|
||||
task_scheduler = TaskScheduler()
|
||||
|
||||
# 示例定时任务函数
|
||||
def example_task():
|
||||
"""示例定时任务"""
|
||||
logger.info("执行示例定时任务")
|
||||
# 这里可以添加具体的业务逻辑
|
||||
return "任务执行完成"
|
||||
|
||||
def database_cleanup_task():
|
||||
"""数据库清理任务示例"""
|
||||
logger.info("执行数据库清理任务")
|
||||
# 这里可以添加数据库清理逻辑
|
||||
return "数据库清理完成"
|
||||
Reference in New Issue
Block a user