详解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中的元组概念
May 21 Python
基于wxpython开发的简单gui计算器实例
May 30 Python
Python实现MySQL操作的方法小结【安装,连接,增删改查等】
Jul 12 Python
Python编程argparse入门浅析
Feb 07 Python
简单实现Python爬取网络图片
Apr 01 Python
对Tensorflow中权值和feature map的可视化详解
Jun 14 Python
python设定并获取socket超时时间的方法
Jan 12 Python
解决PyCharm不运行脚本,而是运行单元测试的问题
Jan 17 Python
Python可变和不可变、类的私有属性实例分析
May 31 Python
python中的django是做什么的
Jul 31 Python
Python Pandas pandas.read_sql_query函数实例用法分析
Jun 21 Python
Python3中最常用的5种线程锁实例总结
Jul 07 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
smarty内置函数config_load用法实例
2015/01/22 PHP
PHP的命令行命令使用指南
2015/08/18 PHP
Yii框架连表查询操作示例
2019/09/06 PHP
原生js 秒表实现代码
2012/07/24 Javascript
dreamweaver 8实现Jquery自动提示
2014/12/04 Javascript
CSS图片响应式 垂直水平居中
2015/08/14 Javascript
JS实现的5级联动Select下拉选择框实例
2015/08/17 Javascript
JavaScript程序开发之JS代码放置的位置
2016/01/15 Javascript
jQuery插件实现带圆点的焦点图片轮播切换
2016/01/18 Javascript
Angular中$compile源码分析
2016/01/28 Javascript
javascript 删除数组元素和清空数组的简单方法
2017/02/24 Javascript
nodejs个人博客开发第二步 入口文件
2017/04/12 NodeJs
BootStrap Table实现server分页序号连续显示功能(当前页从上一页的结束序号开始)
2017/09/12 Javascript
vue-cli构建项目使用 less的方法
2017/10/04 Javascript
Vue+Jwt+SpringBoot+Ldap完成登录认证的示例代码
2018/05/21 Javascript
vue项目打包后打开页面空白解决办法
2018/06/29 Javascript
bootstrap里bootstrap动态加载下拉框的实例讲解
2018/08/10 Javascript
React+Redux实现简单的待办事项列表ToDoList
2019/09/29 Javascript
JS自定义滚动条效果
2020/03/13 Javascript
js在HTML的三种引用方式详解
2020/08/29 Javascript
JS实现简单贪吃蛇小游戏
2020/10/28 Javascript
vue3+typeScript穿梭框的实现示例
2020/12/29 Vue.js
[02:36]DOTA2英雄基础教程 帕格纳
2014/01/20 DOTA
[42:35]2018DOTA2亚洲邀请赛3月30日 小组赛A组 VG VS OpTic
2018/03/31 DOTA
python 制作自定义包并安装到系统目录的方法
2018/10/27 Python
python正则表达式匹配[]中间为任意字符的实例
2018/12/25 Python
python利用 keyboard 库记录键盘事件
2020/10/16 Python
基于OpenCV的路面质量检测的实现
2020/11/04 Python
公务员年总结的自我评价
2013/10/25 职场文书
《圆明园的毁灭》教学反思
2014/02/28 职场文书
本科毕业生求职信
2014/06/15 职场文书
2015年八一建军节慰问信
2015/03/23 职场文书
个人廉政承诺书
2015/04/28 职场文书
党员“一帮一”活动总结
2015/05/07 职场文书
你喜欢篮球吗?Python实现篮球游戏
2021/06/11 Python
我们认为中短波广播场强仪的最佳组合
2022/04/05 无线电