一、简单任务

定义一个函数,然后定义一个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. CKEditor与CKFinder学习--自定义界面及按钮事件捕获

    原文地址:CKEditor与CKFinder学习--自定义界面及按钮事件捕获  讨厌CSDN的广告,吃香太难看! 效果图 界面操作图 原始界面 调整后的界面(删除了flush,表单元素等) 该界面的皮 ...

  2. oracle中的round()方法的用法

    [oracle中的round()方法的用法] Round( ) 函数 传回一个数值,该数值是按照指定的小数位元数进行四舍五入运算的结果 oracle一般常用于计算表空间内存还有多少空间 语法 ROUN ...

  3. bcc-tools工具之profile

    profile是用于追踪程序执行调用流程的工具,类似于perf中的-g指令 相比perf -g而言,profile功能化更加细分,可以根据需要选择追踪层面,例如-U(用户要调用流程) -K (内核态调 ...

  4. 【Codeforces Round #589 (Div. 2) D】Complete Tripartite

    [链接] 我是链接,点我呀:) [题意] 题意 [题解] 其实这道题感觉有点狗. 思路大概是这样 先让所有的点都在1集合中. 然后随便选一个点x,访问它的出度y 显然tag[y]=2 因为和他相连了嘛 ...

  5. NX二次开发-NXOpen方式遍历所有体workPart->Bodies();

    NX11+VS2013 #include <NXOpen/DisplayManager.hxx> #include <NXOpen/Body.hxx> #include < ...

  6. hdu多校第六场1005 (hdu6638) Snowy Smilel 线段树/区间最大和

    题意: 给定一个矩阵,矩阵上有若干点,每个点有正或负的权值,找一个方框框住一些点使得方框中点权值最大. 题解: 离散化横纵坐标,容易将这个问题转化为在矩阵上求最大和子矩阵的问题. 普通的n*n的矩阵的 ...

  7. O(n)线性时间求解第k大-HDU6040-CSU2078

    目录 目录 思路 (有任何问题欢迎留言或私聊 && 欢迎交流讨论哦 目录 HDU6040:传送门  \(m(m\leq 100)\)次查询长度为\(n(n \leq 1e7)\)区间的 ...

  8. Java-Class-@I:org.junit.runner.RunWith

    ylbtech-Java-Class-@I:org.junit.runner.RunWith 1.返回顶部   2.返回顶部   3.返回顶部   4.返回顶部 1. package org.juni ...

  9. AtCoder ABC 132E Hopscotch Addict

    题目链接:https://atcoder.jp/contests/abc132/tasks/abc132_e 题目大意 给定一张 N 个点 M 条边无自环无重边的一张有向图,求从起点 S 能否三步三步 ...

  10. ssrf对redis未授权访问写webshell

    docker建立redis镜像 docker run -d -p 9999:6379 redis 将redis的6379端口映射到物理机的9999端口 使用工具生成攻击代码 攻击 进入容器查看