APScheduler使用

APScheduler (advanceded python scheduler)是一款Python开发的定时任务工具。

文档地址 https://apscheduler.readthedocs.io/en/latest/userguide.html#starting-the-scheduler

特点:

  • 不依赖于Linux系统的crontab系统定时,独立运行

  • 可以动态添加新的定时任务,如

    下单后30分钟内必须支付,否则取消订单,就可以借助此工具(每下一单就要添加此订单的定时任务)

  • 对添加的定时任务可以做持久保存

1 安装

pip install apscheduler 

2 使用方式

from apscheduler.schedulers.background import BackgroundScheduler

# 创建定时任务的调度器对象
scheduler = BackgroundScheduler() # 定义定时任务
def my_job(param1, param2):
pass # 向调度器中添加定时任务
scheduler.add_job(my_job, 'date', args=[100, 'python']) # 启动定时任务调度器工作
scheduler.start()

  

负责管理定时任务

  • BlockingScheduler: 作为独立进程时使用

      from apscheduler.schedulers.blocking import BlockingScheduler
    
      scheduler = BlockingScheduler()
    scheduler.start() # 此处程序会发生阻塞
  • BackgroundScheduler: 在框架程序(如Django、Flask)中使用

    from apscheduler.schedulers.background import BackgroundScheduler
    
      scheduler = BackgroundScheduler()
    scheduler.start() # 此处程序不会发生阻塞

4 执行器 executors

在定时任务该执行时,以进程或线程方式执行任务

  • ThreadPoolExecutor

     from apscheduler.executors.pool import ThreadPoolExecutor
    ThreadPoolExecutor(max_workers)
    ThreadPoolExecutor(20) # 最多20个线程同时执行
     

    使用方法

    executors = {
    'default': ThreadPoolExecutor(20)
    }
    scheduler = BackgroundScheduler(executors=executors)
  • ProcessPoolExecutor

     from apscheduler.executors.pool import ProcessPoolExecutor
    ProcessPoolExecutor(max_workers)
    ProcessPoolExecutor(5) # 最多5个进程同时执行

    使用方法

     executors = {
    'default': ProcessPoolExecutor(3)
    }
    scheduler = BackgroundScheduler(executors=executors)

5 触发器 Trigger

指定定时任务执行的时机

1) date 在特定的时间日期执行

from datetime import date

# 在2019年11月6日00:00:00执行
sched.add_job(my_job, 'date', run_date=date(2009, 11, 6)) # 在2019年11月6日16:30:05
sched.add_job(my_job, 'date', run_date=datetime(2009, 11, 6, 16, 30, 5))
sched.add_job(my_job, 'date', run_date='2009-11-06 16:30:05') # 立即执行
sched.add_job(my_job, 'date')
sched.start()

  

 
  • weeks (int) – number of weeks to wait
  • days (int) – number of days to wait
  • hours (int) – number of hours to wait
  • minutes (int) – number of minutes to wait
  • seconds (int) – number of seconds to wait
  • start_date (datetime|str) – starting point for the interval calculation
  • end_date (datetime|str) – latest possible date/time to trigger on
  • timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations
from datetime import datetime

# 每两小时执行一次
sched.add_job(job_function, 'interval', hours=2) # 在2010年10月10日09:30:00 到2014年6月15日的时间内,每两小时执行一次
sched.add_job(job_function, 'interval', hours=2, start_date='2010-10-10 09:30:00', end_date='2014-06-15 11:00:00')

3) cron 按指定的周期执行

  • year (int|str) – 4-digit year
  • month (int|str) – month (1-12)
  • day (int|str) – day of the (1-31)
  • week (int|str) – ISO week (1-53)
  • day_of_week (int|str) – number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)
  • hour (int|str) – hour (0-23)
  • minute (int|str) – minute (0-59)
  • second (int|str) – second (0-59)
  • start_date (datetime|str) – earliest possible date/time to trigger on (inclusive)
  • end_date (datetime|str) – latest possible date/time to trigger on (inclusive)
  • timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations (defaults to scheduler timezone)
# 在6、7、8、11、12月的第三个周五的00:00, 01:00, 02:00和03:00 执行
sched.add_job(job_function, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3') # 在2014年5月30日前的周一到周五的5:30执行
sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30, end_date='2014-05-30')

方法1

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor executors = {
'default': ThreadPoolExecutor(20),
}
scheduler = BackgroundScheduler(executors=executors)

方法2

from pytz import utc

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ProcessPoolExecutor executors = {
'default': {'type': 'threadpool', 'max_workers': 20},
'processpool': ProcessPoolExecutor(max_workers=5)
} scheduler = BackgroundScheduler() # .. 此处可以编写其他代码 # 使用configure方法进行配置
scheduler.configure(executors=executors)
 

7 启动

scheduler.start() 
  • 对于BlockingScheduler ,程序会阻塞在这,防止退出
  • 对于BackgroundScheduler,程序会立即返回,后台运行

8 扩展

任务管理

方式1

job = scheduler.add_job(myfunc, 'interval', minutes=2)  # 添加任务
job.remove() # 删除任务
job.pause() # 暂定任务
job.resume() # 恢复任务
 

方式2

scheduler.add_job(myfunc, 'interval', minutes=2, id='my_job_id')  # 添加任务
scheduler.remove_job('my_job_id') # 删除任务
scheduler.pause_job('my_job_id') # 暂定任务
scheduler.resume_job('my_job_id') # 恢复任务

调整任务调度周期

job.modify(max_instances=6, name='Alternate name')

scheduler.reschedule_job('my_job_id', trigger='cron', minute='*/5')

停止APScheduler运行

scheduler.shutdown()

Python软件定时器APScheduler使用【软件定时器,非操作系统定时器,软件可控的定时器】【用途:定时同步数据库和缓存等】【刘新宇】的更多相关文章

  1. 定时器任务django-crontab的使用【静态化高频率页面,增加用户体验】【系统的定时器,独立于项目执行】【刘新宇】

    页面静态化 思考: 网页的首页访问频繁,而且查询数据量大,其中还有大量的循环处理. 问题: 用户访问首页会耗费服务器大量的资源,并且响应数据的效率会大大降低. 解决: 页面静态化 1. 页面静态化介绍 ...

  2. JWT验证机制【Python版Flask或自己写的后端可以用】【刘新宇】

    JWT Json Web Token(JWT) JSON Web Token(JWT)是一个非常轻巧的规范.这个规范允许我们使用JWT在两个组织之间传递安全可靠的信息. 官方定义:JSON Web T ...

  3. 进程、线程和携程的通俗解释【刘新宇Python】

    通过下面这张图你就能看清楚了,进程.线程和携程的关系   进程: 多个进程是可以运行在多个CPU当中的,比如你的电脑是4核,可以同时并行运行四个进程,这是真正物理上的并行运行. 线程: 每个进程又可以 ...

  4. 用Python写一款属于自己的 简易zip压缩软件 附完成图(适合初学者)

    一.软件描述 用Python tkinter模块写一款属于自己的压缩软件.zip文件格式是通用的文档压缩标准,在ziplib模块中,使用ZipFile来操作zip文件,具有功能:zip压缩功能,zip ...

  5. (原创)对比组态软件,使用C#开发的服务器和客户端软件的优势

    在当前经济形势和市场环境下,中小企业面对萧条的消费市场,恶化的外部贸易环境,刚性支出高成本人工和生产要素,通货膨胀,隐性的腐化支出等各种因素的作用导致企业生存艰难,企业需要在各方面削减支出,拓展市场寻 ...

  6. python 定时任务 from apscheduler.schedulers.blocking import BlockingScheduler

    说明:使用python内置的模块来实现,本篇博客只是以循环定时来示范,其他的可以结合crontab的风格自己设定 一.导包 from apscheduler.schedulers.blocking i ...

  7. Python 定时任务框架 APScheduler 详解

    APScheduler 最近想写个任务调度程序,于是研究了下 Python 中的任务调度工具,比较有名的是:Celery,RQ,APScheduler. Celery:非常强大的分布式任务调度框架 R ...

  8. R软件导入数据_r语言怎么导入数据_R软件导入数据

    R软件导入数据_r语言怎么导入数据_R软件导入数据 R软件导入数据 1.Rcmdr安装包导入数据: 1.安装Rcmdr包,输入: install.packages("Rcmdr") ...

  9. linux安装软件的几种方法----linux下编译安装软件的一般步骤

    linux安装软件的几种方法: 一.rpm包安装方式步骤: 1.找到相应的软件包,比如soft.version.rpm,下载到本机某个目录: 2.打开一个终端,su -成root用户: 3.cd so ...

随机推荐

  1. iOS 内存分配与分区

    RAM ROM RAM:运行内存,不能掉电存储. ROM:存储性内存,可以掉电存储,例如内存卡.Flash. 由于 RAM 类型不具备掉电存储能力(即一掉电数据消失),所以 app 程序一般存放于 R ...

  2. Mysql数据库主键,外键,索引概述

    主键: 主键是数据表的唯一索引,比如学生表里有学号和姓名,姓名可能有重名的,但学号确是唯一的,你要从学生表中搜索一条纪录如查找一个人,就只能根据学号去查找,这才能找出唯一的一个,这就是主键;如:id ...

  3. Python学习笔记:String类型所有方法汇总

    # 按字母表熟悉下string中的方法# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z# 标红的为常用重点的方法!! str = " ...

  4. Unity 阴影淡入淡出效果中Shader常量 unity_ShadowFadeCenterAndType和_LightShadowData的问题

    由于Universal Render Pipeline目前(2020年4月1日)把阴影淡入淡出这个功能竟然给取消了…我自己拿片元位置到相机位置的距离进行了一个淡化,但是阴影边缘老是被裁切…后来研究了一 ...

  5. [noip模拟]散步<dp>

    题目链接:http://begin.lydsy.com/JudgeOnline/problem.php?id=2097 这题A的时候,百感交集五味杂陈............ 就这么一道看起来简单的不 ...

  6. 如何在Linux下优雅的查询日志

    做为一名合格的Java后台开发 经常需要查询线上的日志,定位线上问题 所以熟练掌握日志查询的命令 可以使你更加迅速的定位错误日志位置,及时解决问题 在此,我将介绍几个自己工作中经常使用到的日志查询命令 ...

  7. 新建jsp文件,The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path错误解决方法

    新建一个jsp文件后,有一个错误,The superclass "javax.servlet.http.HttpServlet" was not found on the Java ...

  8. Pytest系列(7) - skip、skipif跳过用例

    如果你还想从头学起Pytest,可以看看这个系列的文章哦! https://www.cnblogs.com/poloyy/category/1690628.html 前言 pytest.mark.sk ...

  9. @Configuration和@Bean 配置类注入

    @Configuration和@Bean 1. 概述 @Configuration 注解标记在类上, 就像下面的配置文件. 我们将该类成为配置类. <?xml version="1.0 ...

  10. C# 快速开发框架搭建—环境搭建

    一.新建MVC项目 打开vs2013新建空的解决方案,在解决方案中增加一个MVC项目,如图: 删除不需要的文件,剩下如图所示的文件夹: 首先创建一个MVC5控制器(Login,登入使用),该控制器无需 ...