• APScheduler -调度器 BlockingScheduler


    schedulers 调度器主要分三种,一种独立运行的,一种是后台运行的,最后一种是配合其它程序使用

    • BlockingScheduler: 当这个调度器是你应用中 唯一要运行 的东西时使用
    • BackgroundScheduler: 当 不运行其它框架 的时候使用,并使你的任务在 后台运行
    • AsyncIOScheduler: 当你的程序是 异步IO模型 的时候使用

    BlockingScheduler

    当你的应用中,仅仅只运行定时任务,其它代码都不执行的时候,可以用到BlockingScheduler 调度器。比如你写了一个简单的程序,设置一个定时任务去抓取页面的数据。那就可以用到BlockingScheduler.
    或者你单独去调试看定时任务有没执行

    from apscheduler.schedulers.blocking import BlockingScheduler  
    import time  
      
      
    # 仅运行定时任务  
    scheduler = BlockingScheduler()  
      
      
    # 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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    运行结果

    task 2 executed  yyy-------- 1698211090.014796
    task 2 executed  yyy-------- 1698211095.0198605
    task 1 executed  xxxx-------- 1698211097.7044744
    task 2 executed  yyy-------- 1698211100.0056248
    task 2 executed  yyy-------- 1698211105.0121682
    task 1 executed  xxxx-------- 1698211107.6990259
    task 2 executed  yyy-------- 1698211110.0029516
    task 2 executed  yyy-------- 1698211115.011106
    task 1 executed  xxxx-------- 1698211117.699221
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    scheduler.start()

    scheduler.start() 调用会阻塞主线程

    # 添加一个定时任务  
    scheduler.add_job(  
        task2, 'cron', second='*/5',  
        args=["yyy"], id="task_2", replace_existing=True  
    )  
      
    scheduler.start()  
      
    while(True):  
        print('main ---------------')  
        time.sleep(1)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    如果后面还有其它代码,会一直没法执行。

    如果有其它代码需要执行,可以使用BackgroundScheduler,使你的任务在 后台运行

  • 相关阅读:
    ​Mac还是Windows好?适合自己的可能才是最好的
    MySQL语法笔记(自用)
    cas:216300-12-8|1-丙基-3-甲基咪唑六氟磷酸盐[C3MIm]PF6离子液体分子量:125
    TI mmWave radar sensors Tutorial 笔记 | Module 3: Velocity Estimation
    浅尝 ECDHE 协议流程
    php实战案例记录(8)去除XSS的函数
    通过Git Bash将本地文件上传到本地github
    DevOps最佳实践之应用开发和部署
    Ubuntu18.04双系统 + ROS Melodic + RoboRTS安装教程
    设计模式在芯片验证中的应用——装饰器
  • 原文地址:https://blog.csdn.net/qq_27371025/article/details/134087041