详解python调度框架APScheduler使用


Posted in Python onMarch 28, 2017

最近在研究python调度框架APScheduler使用的路上,那么今天也算个学习笔记吧!

# coding=utf-8
"""
Demonstrates how to use the background scheduler to schedule a job that executes on 3 second
intervals.
"""

from datetime import datetime
import time
import os

from apscheduler.schedulers.background import BackgroundScheduler


def tick():
  print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
  scheduler = BackgroundScheduler()
  scheduler.add_job(tick, 'interval', seconds=3)#间隔3秒钟执行一次
  scheduler.start()  #这里的调度任务是独立的一个线程
  print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

  try:
    # This is here to simulate application activity (which keeps the main thread alive).
    while True:
      time.sleep(2)  #其他任务是独立的线程执行
      print('sleep!')
  except (KeyboardInterrupt, SystemExit):
    # Not strictly necessary if daemonic mode is enabled but should be done if possible
    scheduler.shutdown()
    print('Exit The Job!')

非阻塞调度,在指定的时间执行一次

# coding=utf-8
"""
Demonstrates how to use the background scheduler to schedule a job that executes on 3 second
intervals.
"""

from datetime import datetime
import time
import os

from apscheduler.schedulers.background import BackgroundScheduler


def tick():
  print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
  scheduler = BackgroundScheduler()
  #scheduler.add_job(tick, 'interval', seconds=3)
  scheduler.add_job(tick, 'date', run_date='2016-02-14 15:01:05')#在指定的时间,只执行一次
  scheduler.start()  #这里的调度任务是独立的一个线程
  print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

  try:
    # This is here to simulate application activity (which keeps the main thread alive).
    while True:
      time.sleep(2)  #其他任务是独立的线程执行
      print('sleep!')
  except (KeyboardInterrupt, SystemExit):
    # Not strictly necessary if daemonic mode is enabled but should be done if possible
    scheduler.shutdown()
    print('Exit The Job!')

非阻塞的方式,采用cron的方式执行

# coding=utf-8
"""
Demonstrates how to use the background scheduler to schedule a job that executes on 3 second
intervals.
"""

from datetime import datetime
import time
import os

from apscheduler.schedulers.background import BackgroundScheduler


def tick():
  print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
  scheduler = BackgroundScheduler()
  #scheduler.add_job(tick, 'interval', seconds=3)
  #scheduler.add_job(tick, 'date', run_date='2016-02-14 15:01:05')
  scheduler.add_job(tick, 'cron', day_of_week='6', second='*/5')
  '''
    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)
  
    *  any  Fire on every value
    */a  any  Fire every a values, starting from the minimum
    a-b  any  Fire on any value within the a-b range (a must be smaller than b)
    a-b/c  any  Fire every c values within the a-b range
    xth y  day  Fire on the x -th occurrence of weekday y within the month
    last x  day  Fire on the last occurrence of weekday x within the month
    last  day  Fire on the last day within the month
    x,y,z  any  Fire on any matching expression; can combine any number of any of the above expressions
  '''
  scheduler.start()  #这里的调度任务是独立的一个线程
  print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

  try:
    # This is here to simulate application activity (which keeps the main thread alive).
    while True:
      time.sleep(2)  #其他任务是独立的线程执行
      print('sleep!')
  except (KeyboardInterrupt, SystemExit):
    # Not strictly necessary if daemonic mode is enabled but should be done if possible
    scheduler.shutdown()
    print('Exit The Job!')

阻塞的方式,间隔3秒执行一次

# coding=utf-8
"""
Demonstrates how to use the background scheduler to schedule a job that executes on 3 second
intervals.
"""

from datetime import datetime
import os

from apscheduler.schedulers.blocking import BlockingScheduler


def tick():
  print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
  scheduler = BlockingScheduler()
  scheduler.add_job(tick, 'interval', seconds=3)
  
  print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

  try:
    scheduler.start()  #采用的是阻塞的方式,只有一个线程专职做调度的任务
  except (KeyboardInterrupt, SystemExit):
    # Not strictly necessary if daemonic mode is enabled but should be done if possible
    scheduler.shutdown()
    print('Exit The Job!')

采用阻塞的方法,只执行一次

# coding=utf-8
"""
Demonstrates how to use the background scheduler to schedule a job that executes on 3 second
intervals.
"""

from datetime import datetime
import os

from apscheduler.schedulers.blocking import BlockingScheduler


def tick():
  print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
  scheduler = BlockingScheduler()
  scheduler.add_job(tick, 'date', run_date='2016-02-14 15:23:05')
  
  print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

  try:
    scheduler.start()  #采用的是阻塞的方式,只有一个线程专职做调度的任务
  except (KeyboardInterrupt, SystemExit):
    # Not strictly necessary if daemonic mode is enabled but should be done if possible
    scheduler.shutdown()
    print('Exit The Job!')

采用阻塞的方式,使用cron的调度方法

# coding=utf-8
"""
Demonstrates how to use the background scheduler to schedule a job that executes on 3 second
intervals.
"""

from datetime import datetime
import os

from apscheduler.schedulers.blocking import BlockingScheduler


def tick():
  print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
  scheduler = BlockingScheduler()
  scheduler.add_job(tick, 'cron', day_of_week='6', second='*/5')
  '''
    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)
  
    *  any  Fire on every value
    */a  any  Fire every a values, starting from the minimum
    a-b  any  Fire on any value within the a-b range (a must be smaller than b)
    a-b/c  any  Fire every c values within the a-b range
    xth y  day  Fire on the x -th occurrence of weekday y within the month
    last x  day  Fire on the last occurrence of weekday x within the month
    last  day  Fire on the last day within the month
    x,y,z  any  Fire on any matching expression; can combine any number of any of the above expressions
  '''
  
  print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

  try:
    scheduler.start()  #采用的是阻塞的方式,只有一个线程专职做调度的任务
  except (KeyboardInterrupt, SystemExit):
    # Not strictly necessary if daemonic mode is enabled but should be done if possible
    scheduler.shutdown()
    print('Exit The Job!')

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现拼接多张图片的方法
Dec 01 Python
python实现分析apache和nginx日志文件并输出访客ip列表的方法
Apr 04 Python
在Python中使用poplib模块收取邮件的教程
Apr 29 Python
python学习之第三方包安装方法(两种方法)
Jul 30 Python
通过实例浅析Python对比C语言的编程思想差异
Aug 30 Python
对Python中class和instance以及self的用法详解
Jun 26 Python
Pytorch.nn.conv2d 过程验证方式(单,多通道卷积过程)
Jan 03 Python
Anaconda3+tensorflow2.0.0+PyCharm安装与环境搭建(图文)
Feb 18 Python
Python logging模块异步线程写日志实现过程解析
Jun 30 Python
python3中确保枚举值代码分析
Dec 02 Python
pycharm 使用anaconda为默认环境的操作
Feb 05 Python
利用python实现汉诺塔游戏
Mar 01 Python
Python中is与==判断的区别
Mar 28 #Python
Python利用Beautiful Soup模块创建对象详解
Mar 27 #Python
Python利用Beautiful Soup模块修改内容方法示例
Mar 27 #Python
python递归查询菜单并转换成json实例
Mar 27 #Python
Python中的命令行参数解析工具之docopt详解
Mar 27 #Python
Python使用PDFMiner解析PDF代码实例
Mar 27 #Python
详解python并发获取snmp信息及性能测试
Mar 27 #Python
You might like
PHP不用递归实现无限分级的例子分享
2014/04/18 PHP
php的XML文件解释类应用实例
2014/09/22 PHP
完美解决在ThinkPHP控制器中命名空间的问题
2017/05/05 PHP
基于jquery 的一个progressbar widge
2010/10/29 Javascript
基于jquery的一个OutlookBar类,动态创建导航条
2010/11/19 Javascript
JS的replace方法介绍
2012/10/20 Javascript
深入理解JavaScript系列(40):设计模式之组合模式详解
2015/03/04 Javascript
基于jQuery和CSS3制作响应式水平时间轴附源码下载
2015/12/20 Javascript
JavaScript实现刷新不重记的倒计时
2016/08/10 Javascript
jQuery基于ajax操作json数据简单示例
2017/01/05 Javascript
深究AngularJS中ng-drag、ng-drop的用法
2017/06/12 Javascript
浅谈vuejs实现数据驱动视图原理
2018/02/23 Javascript
vue 项目 iOS WKWebView 加载
2019/04/17 Javascript
微信小程序获取复选框全选反选选中的值(实例代码)
2019/12/17 Javascript
功能完善的小程序日历组件的实现
2020/03/31 Javascript
jQuery 添加元素和删除元素的方法
2020/07/15 jQuery
超详细小程序定位地图模块全系列开发教学
2020/11/24 Javascript
[01:03:41]完美世界DOTA2联赛PWL S3 DLG vs Phoenix 第一场 12.17
2020/12/19 DOTA
Python基于列表模拟堆栈和队列功能示例
2018/01/05 Python
Python设计模式之观察者模式简单示例
2018/01/10 Python
Python获取二维矩阵每列最大值的方法
2018/04/03 Python
Python3的高阶函数map,reduce,filter的示例详解
2019/07/23 Python
python 中值滤波,椒盐去噪,图片增强实例
2019/12/18 Python
Pytorch1.5.1版本安装的方法步骤
2020/12/31 Python
CSS3中的元素过渡属性transition示例详解
2016/11/30 HTML / CSS
html5 web本地存储将取代我们的cookie
2012/12/26 HTML / CSS
使用canvas绘制超炫时钟
2014/12/17 HTML / CSS
Envie de Fraise意大利:法国网上推出的孕妇装品牌
2020/10/18 全球购物
手机促销活动方案
2014/02/05 职场文书
总经理工作职责范文
2014/03/14 职场文书
股权转让协议书范本
2014/04/12 职场文书
婚宴致辞
2015/07/28 职场文书
怎样做好公众演讲能力?
2019/08/28 职场文书
导游词之丽江普济寺
2019/10/22 职场文书
vue中使用mockjs配置和使用方式
2022/04/06 Vue.js
SpringBoot使用AOP实现统计全局接口访问次数详解
2022/06/16 Java/Android