详解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 21 Python
Python使用Paramiko模块编写脚本进行远程服务器操作
May 05 Python
Python3 循环语句(for、while、break、range等)
Nov 20 Python
Python数据处理numpy.median的实例讲解
Apr 02 Python
Python2和Python3之间的str处理方式导致乱码的讲解
Jan 03 Python
Tensorflow分类器项目自定义数据读入的实现
Feb 05 Python
使用Python画股票的K线图的方法步骤
Jun 28 Python
pandas的qcut()方法详解
Jul 06 Python
如何实现更换Jupyter Notebook内核Python版本
May 18 Python
Python中的整除和取模实例
Jun 03 Python
详解pandas获取Dataframe元素值的几种方法
Jun 14 Python
Python 避免字典和元组的多重嵌套问题
Jul 15 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
咖啡界又出新概念,无需咖啡豆的分子咖啡
2021/03/03 咖啡文化
PHP中用hash实现的数组
2011/07/17 PHP
功能强大的PHP POST提交数据类
2016/07/15 PHP
Zend Framework处理Json数据方法详解
2016/12/09 PHP
Laravel框架FormRequest中重写错误处理的方法
2019/02/18 PHP
JavaScript实现QueryString获取GET参数的方法
2013/07/02 Javascript
jquery取消选择select下拉框示例代码
2014/02/22 Javascript
解决用jquery load加载页面到div时,不执行页面js的问题
2014/02/22 Javascript
jquery选择器原理介绍($()使用方法)
2014/03/25 Javascript
jQuery Mobile中的button按钮组件基础使用教程
2016/05/23 Javascript
JSONP跨域请求实例详解
2016/07/04 Javascript
jQuery实现点击下拉框中的值累加到文本框中的方法示例
2017/10/28 jQuery
Vue ElementUI实现:限制输入框只能输入正整数的问题
2020/07/31 Javascript
vue使用echarts实现水平柱形图实例
2020/09/09 Javascript
ant design vue导航菜单与路由配置操作
2020/10/28 Javascript
微信小程序实现页面监听自定义组件的触发事件
2020/11/01 Javascript
python结合opencv实现人脸检测与跟踪
2015/06/08 Python
Linux下将Python的Django项目部署到Apache服务器
2015/12/24 Python
python实现用户登录系统
2016/05/21 Python
Python实现带百分比的进度条
2016/06/28 Python
Linux 下 Python 实现按任意键退出的实现方法
2016/09/25 Python
python截取两个单词之间的内容方法
2018/12/25 Python
python内存动态分配过程详解
2019/07/15 Python
Python编写单元测试代码实例
2020/09/10 Python
css3旋转木马_动力节点Java学院整理
2017/07/12 HTML / CSS
canvas烟花特效锦集
2018/01/17 HTML / CSS
护理专业毕业生自我鉴定
2013/10/08 职场文书
2014迎新年晚会策划方案
2014/02/23 职场文书
食品安全工作实施方案
2014/03/26 职场文书
违反交通法规检讨书
2014/09/10 职场文书
先进典型发言材料
2014/12/30 职场文书
情人节活动总结范文
2015/02/05 职场文书
集结号观后感
2015/06/08 职场文书
超市啤酒狂欢夜策划方案范文!
2019/07/03 职场文书
小程序后台PHP版本部署运行 LNMP+WNMP
2021/04/01 Servers
React 高阶组件HOC用法归纳
2021/06/13 Javascript