APScheduler-调度器 BackgroundScheduler

当你有主程序需要执行,让定时任务在后台执行时,可以用BackgroundScheduler

python 复制代码
from apscheduler.schedulers.background import BackgroundScheduler  
import time  
  
  
# 仅运行定时任务  
scheduler = BackgroundScheduler()  
  
  
# interval example, 间隔执行, 每10秒执行一次  
def task1(x):  
    print(f'task 1 executed  {x}--------', time.time())  
  
  
# 添加一个定时任务  
scheduler.add_job(  
    task1, 'interval', seconds=10,  
    args=["xxxx"], id="task_1", replace_existing=True  
)  
  
  
# cron examples, 每5秒执行一次 相当于interval 间隔调度中seconds = 5  
def task2(y):  
    print(f'task 2 executed  {y}--------', time.time())  
  
  
# 添加一个定时任务  
scheduler.add_job(  
    task2, 'cron', second='*/5',  
    args=["yyy"], id="task_2", replace_existing=True  
)  
  
scheduler.start()  
  
while(True):  
    print('main ---------------')  
    time.sleep(1)

执行结果

复制代码
main ---------------
main ---------------
main ---------------
main ---------------
task 2 executed  yyy-------- 1698211520.0085256
main ---------------
main ---------------

Flask-APScheduler 中默认使用的就是 BackgroundScheduler

相关推荐
0566466 小时前
agent学习Day15——SQLAlchemy 查询过滤、分页与历史列表接口
python·学习·fastapi
程序员爱德华7 小时前
Python与C++:异同点对比
c++·python
hangyuekejiGEO8 小时前
GEO技术服务选型指南
大数据·人工智能·python
软萌萌的18 小时前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
Dxy12393102169 小时前
Linux 编译安装 Python 3.12.10(多版本共存,不破坏系统Python)
linux·运维·python
持敬chijing10 小时前
Python概述
开发语言·python
赤羽尾风12 小时前
NumPy快速入门
python·numpy
倒流时光三十年12 小时前
第三阶段 26 · highlight 高亮(返回命中片段)
后端·python·django
久久学姐14 小时前
Python+Playwright+Pytest+BDD,用FSM打造高效测试框架
python·pytest·bdd·playwright·fsm