一、简单任务

定义一个函数,然后定义一个scheduler类型,添加一个job,然后执行,就可以了

5秒整倍数,就执行这个函数

# coding:utf-8
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime def aps_test():
print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), '你好') scheduler = BlockingScheduler()
scheduler.add_job(func=aps_test, trigger='cron', second='*/5')
scheduler.start()

带参数的

# coding:utf-8
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime def aps_test(x):
print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x) scheduler = BlockingScheduler()
scheduler.add_job(func=aps_test, args=('你好',), trigger='cron', second='*/5')
scheduler.start()
# coding:utf-8
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime def aps_test(x):
print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x) scheduler = BlockingScheduler()
scheduler.add_job(func=aps_test, args=('定时任务',), trigger='cron', second='*/5')
scheduler.add_job(func=aps_test, args=('一次性任务',), next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=12))
scheduler.add_job(func=aps_test, args=('循环任务',), trigger='interval', seconds=3) scheduler.start()

二、日志

# coding:utf-8
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
import logging logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='log1.txt',
filemode='a') def aps_test(x):
print 1/0
print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x) scheduler = BlockingScheduler()
scheduler.add_job(func=aps_test, args=('定时任务',), trigger='cron', second='*/5')
scheduler._logger = logging
scheduler.start()

三、删除任务

要求执行一定阶段任务以后,删除某一个循环任务,其他任务照常进行。有如下代码:

# coding:utf-8
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
import logging logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='log1.txt',
filemode='a') def aps_test(x):
print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x) def aps_date(x):
scheduler.remove_job('interval_task')
print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x) scheduler = BlockingScheduler()
scheduler.add_job(func=aps_test, args=('定时任务',), trigger='cron', second='*/5', id='cron_task')
scheduler.add_job(func=aps_date, args=('一次性任务,删除循环任务',), next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=12), id='date_task')
scheduler.add_job(func=aps_test, args=('循环任务',), trigger='interval', seconds=3, id='interval_task')
scheduler._logger = logging scheduler.start()

四、停止任务,恢复任务

# coding:utf-8
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
import logging logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='log1.txt',
filemode='a') def aps_test(x):
print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x) def aps_pause(x):
scheduler.pause_job('interval_task')
print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x) def aps_resume(x):
scheduler.resume_job('interval_task')
print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x) scheduler = BlockingScheduler()
scheduler.add_job(func=aps_test, args=('定时任务',), trigger='cron', second='*/5', id='cron_task')
scheduler.add_job(func=aps_pause, args=('一次性任务,停止循环任务',), next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=12), id='pause_task')
scheduler.add_job(func=aps_resume, args=('一次性任务,恢复循环任务',), next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=24), id='resume_task')
scheduler.add_job(func=aps_test, args=('循环任务',), trigger='interval', seconds=3, id='interval_task')
scheduler._logger = logging scheduler.start()

五、捕获错误

# coding:utf-8
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
import datetime
import logging logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='log1.txt',
filemode='a') def aps_test(x):
print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x) def date_test(x):
print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x)
print (1/0) def my_listener(event):
if event.exception:
print ('任务出错了!!!!!!')
else:
print ('任务照常运行...') scheduler = BlockingScheduler()
scheduler.add_job(func=date_test, args=('一定性任务,会出错',), next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=15), id='date_task')
scheduler.add_job(func=aps_test, args=('循环任务',), trigger='interval', seconds=3, id='interval_task')
scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
scheduler._logger = logging scheduler.start()

六、定时任务的接口设计

# 定时任务功能
@admin.route('/pause', methods=['POST'])
@user_login_req
def pausetask(): # 停止
data = request.form.get('task_id')
job = scheduler.get_job(str(data))
res = {}
if job:
if 'pause' in job.__str__():
res.update({'status': 1001, 'msg': '已停止'})
else:
scheduler.pause_job(str(data))
res.update({'status': 1000, 'msg': '停止中'})
else:
res.update({'status': 1001, 'msg': '未运行'})
return jsonify(res) @admin.route('/resume', methods=['POST'])
@user_login_req
def resumetask(): # 恢复
data = request.form.get('task_id')
job=scheduler.get_job(str(data))
res={}
if job:
if 'run' in job.__str__():
res.update({'status':1001,'msg':'已恢复'})
else:
scheduler.resume_job(str(data))
res.update({'status': 1000, 'msg': '恢复中'})
else:
res.update({'status':1001,'msg':'未运行'})
return jsonify(res) @admin.route('/remove_task', methods=['POST'])
@user_login_req
def remove_task(): # 移除
data = request.form['task_id']
job = scheduler.get_job(str(data))
res = {}
if not job:
res.update({'status': 1001, 'msg': '已删除'})
else:
scheduler.remove_job(str(data))
res.update({'status': 1000, 'msg': '删除中'})
return jsonify(res) @admin.route('/addjob', methods=['POST'])
@user_login_req
def addtask():
data = request.form.get('task_id') job = scheduler.get_job(str(data))
if job:
return jsonify({'status': 1001,'msg':'已开启'})
if data == '':
scheduler.add_job(func=task1, id='', trigger='cron', day_of_week='0-6', hour=18, minute=19,
second=10,
replace_existing=True)
# trigger='cron' 表示是一个定时任务
else:
scheduler.add_job(func=task2, id='', trigger='interval', seconds=10,
replace_existing=True)
# trigger='interval' 表示是一个循环任务,每隔多久执行一次
return jsonify({'status': 1000,'msg':'运行中'}) def task1():
print('mession1')
print(datetime.datetime.now()) def task2():
print('mession2')
print(datetime.datetime.now())

python定时任务模块APScheduler的更多相关文章

  1. Python定时任务框架APScheduler

    http://blog.csdn.net/chosen0ne/article/details/7842421 APScheduler是基于Quartz的一个Python定时任务框架,实现了Quartz ...

  2. [转]Python定时任务框架APScheduler

    APScheduler是基于Quartz的 一个Python定时任务框架,实现了Quartz的所有功能,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以 持久化任务 ...

  3. 定时任务模块——APScheduler

    一.概念: python定时任务框架,基于日期,固定时间间隔,crontab类型的任务,并且可以持久化任务,并能以deamon守护方式运行任务 二.简介: 安装:pip install apsched ...

  4. python 定时任务框架apscheduler

    文章目录 安装 基本概念介绍 调度器的工作流程 实例1 -间隔性任务 实例2 - cron 任务 配置调度器 方法一 方法二 方法三: 启动调度器 方法一:使用默认的作业存储器: 方法二:使用数据库作 ...

  5. Python定时任务利器—Apscheduler

    导语 在工作场景遇到了这么一个场景,就是需要定期去执行一个缓存接口,用于同步设备配置.首先想到的就是Linux上的crontab,可以定期,或者间隔一段时间去执行任务.但是如果你想要把这个定时任务作为 ...

  6. Python定时任务框架APScheduler 3.0.3 Cron示例

    APScheduler是基于Quartz的一个Python定时任务框架,实现了Quartz的所有功能,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以持久化任务.基 ...

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

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

  8. 分布式定时任务框架——python定时任务框架APScheduler扩展

    http://bbs.7boo.org/forum.php?mod=viewthread&tid=14546 如果将定时任务部署在一台服务器上,那么这个定时任务就是整个系统的单点,这台服务器出 ...

  9. python定时任务:apscheduler的使用(还有一个celery~)

    文章摘自:https://www.cnblogs.com/luxiaojun/p/6567132.html 1 . 安装 pip install apscheduler 2 . 简单例子 # codi ...

随机推荐

  1. UTF-8 - ASCII 兼容的多字节 Unicode 编码

    描述 The Unicode 字符集使用的是 16 位(双字节)码.最普遍的 Unicode 编码方法( UCS-2) 由一个 16 位双字序列组成.这样的字符串中包括了的一些如‘\0’或‘/’这样的 ...

  2. [LOJ#2732] 「JOISC 2016 Day 2」雇佣计划

    参考博文 (不过个人感觉我讲的稍微更清楚一点) 题目就是让我们求图中满足数值大于等于B的连通块数量 然后我们可以尝试转换为求连通块两端所产生的“谷”的数量,显然一个连通块对谷可以贡献2的答案,最终答案 ...

  3. nodejs route的简单使用

    demo var express=require('express'); var app=express(); var routeUser=express.Router(); var routeTea ...

  4. Vuejs input 和 textarea 元素中使用 v-model 实现双向数据绑定

    demo <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <titl ...

  5. Atcoder arc092

    E-Both Sides Merger 给你一个序列,支持两种操作,直到序列中只有一个数时停下来,使得剩下数最大,并输出选数方案. 操作1:扔掉一个最前端或最后端的元素.操作2:选取一个不在边界上的元 ...

  6. 二分法的应用:最大化最小值 POJ2456 Aggressive cows

    /* 二分法的应用:最大化最小值 POJ2456 Aggressive cows Time Limit: 1000MS Memory Limit: 65536K Total Submissions: ...

  7. 「题解」:y

    问题 B: y 时间限制: 1 Sec  内存限制: 256 MB 题面 题面谢绝公开. 题解 考虑双向搜索. 定义$cal_{i,j,k}$表示当前已经搜索状态中是否存在长度为i,终点为j,搜索过边 ...

  8. jQuery方法判断checkbox是否选中以及改变checkbox的选中状态

    jquery判断checked的三种方法: .attr('checked):   //看版本1.6+返回:”checked”或”undefined” ;1.5-返回:true或false .prop( ...

  9. hdu4352-XHXJ's LIS状压DP+数位DP

    (有任何问题欢迎留言或私聊 && 欢迎交流讨论哦 题意:传送门  原题目描述在最下面.  在区间内把整数看成一个阿拉伯数字的集合,此集合中最长严格上升子序列的长度为k的个数. 思路: ...

  10. ionic-CSS:ionic tab(选项卡)

    ylbtech-ionic-CSS:ionic tab(选项卡) 1.返回顶部 1. ionic tab(选项卡) ionic tab(选项卡) 是水平排列的按钮或者链接,用以页面间导航的切换.它可以 ...