详解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中的hashlib和base64加密模块使用实例
Sep 02 Python
python排序方法实例分析
Apr 30 Python
python 用lambda函数替换for循环的方法
Jun 09 Python
python 计算数据偏差和峰度的方法
Jun 29 Python
基于python的selenium两种文件上传操作实现详解
Sep 19 Python
python求绝对值的三种方法小结
Dec 04 Python
Python+OpenCV 实现图片无损旋转90°且无黑边
Dec 12 Python
Python lxml模块的基本使用方法分析
Dec 21 Python
Python GUI自动化实现绕过验证码登录
Jan 10 Python
python GUI库图形界面开发之PyQt5线程类QThread详细使用方法
Feb 26 Python
用Python爬取LOL所有的英雄信息以及英雄皮肤的示例代码
Jul 13 Python
利用Python实现自动扫雷小脚本
Dec 17 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 高级课程笔记 面向对象
2009/06/21 PHP
php smarty模版引擎中的缓存应用
2009/12/11 PHP
php Smarty模板生成html文档的方法
2010/04/12 PHP
Laravel Reponse响应客户端示例详解
2020/09/03 PHP
ExtJs使用IFrame的实现代码
2010/03/24 Javascript
使用jQuery的将桌面应用程序引入浏览器
2010/11/19 Javascript
JavaScript实现的使用键盘控制人物走动实例
2014/08/27 Javascript
流量统计器如何鉴别C#:WebBrowser中伪造referer
2015/01/07 Javascript
快速学习jQuery插件 jquery.validate.js表单验证插件使用方法
2015/12/01 Javascript
React.js入门学习第一篇
2016/03/30 Javascript
bootstrap布局中input输入框右侧图标点击功能
2016/05/16 Javascript
页面间固定参数,通过cookie传值的实现方法
2017/05/31 Javascript
详解vue组件通信的三种方式
2017/06/30 Javascript
VueJs监听window.resize方法示例
2018/01/17 Javascript
Vue2.0中三种常用传值方式(父传子、子传父、非父子组件传值)
2018/08/16 Javascript
Node.js原生api搭建web服务器的方法步骤
2019/02/15 Javascript
js实现移动端tab切换时下划线滑动效果
2019/09/08 Javascript
微信小程序 wx.getUserInfo引导用户授权问题实例分析
2020/03/09 Javascript
在Python中操作字典之clear()方法的使用
2015/05/21 Python
Python使用turtule画五角星的方法
2015/07/09 Python
Python中的复制操作及copy模块中的浅拷贝与深拷贝方法
2016/07/02 Python
Python 从列表中取值和取索引的方法
2018/12/25 Python
Ubuntu18.04下python版本完美切换的解决方法
2019/06/14 Python
使用Python实现图像标记点的坐标输出功能
2019/08/14 Python
Python使用ElementTree美化XML格式的操作
2020/03/06 Python
jupyter notebook实现显示行号
2020/04/13 Python
python中的测试框架
2020/11/13 Python
Crucial英睿达法国官网:内存条及SSD固态硬盘升级
2018/07/13 全球购物
德国价格合理的品牌商品购物网站:averdo
2019/03/21 全球购物
小学教育毕业生自荐信
2013/11/18 职场文书
实用求职信范文分享
2013/12/25 职场文书
学生会竞选演讲稿怎么写
2014/08/26 职场文书
企业财务管理制度范本
2015/08/04 职场文书
小学作文指导之如何写人?
2019/07/08 职场文书
nginx location中多个if里面proxy_pass的方法
2021/03/31 Servers
Python写情书? 10行代码展示如何把情书写在她的照片里
2022/04/21 Python