python定时任务模块APScheduler
一、简单任务
定义一个函数,然后定义一个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的更多相关文章
- Python定时任务框架APScheduler
http://blog.csdn.net/chosen0ne/article/details/7842421 APScheduler是基于Quartz的一个Python定时任务框架,实现了Quartz ...
- [转]Python定时任务框架APScheduler
APScheduler是基于Quartz的 一个Python定时任务框架,实现了Quartz的所有功能,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以 持久化任务 ...
- 定时任务模块——APScheduler
一.概念: python定时任务框架,基于日期,固定时间间隔,crontab类型的任务,并且可以持久化任务,并能以deamon守护方式运行任务 二.简介: 安装:pip install apsched ...
- python 定时任务框架apscheduler
文章目录 安装 基本概念介绍 调度器的工作流程 实例1 -间隔性任务 实例2 - cron 任务 配置调度器 方法一 方法二 方法三: 启动调度器 方法一:使用默认的作业存储器: 方法二:使用数据库作 ...
- Python定时任务利器—Apscheduler
导语 在工作场景遇到了这么一个场景,就是需要定期去执行一个缓存接口,用于同步设备配置.首先想到的就是Linux上的crontab,可以定期,或者间隔一段时间去执行任务.但是如果你想要把这个定时任务作为 ...
- Python定时任务框架APScheduler 3.0.3 Cron示例
APScheduler是基于Quartz的一个Python定时任务框架,实现了Quartz的所有功能,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以持久化任务.基 ...
- Python 定时任务框架 APScheduler 详解
APScheduler 最近想写个任务调度程序,于是研究了下 Python 中的任务调度工具,比较有名的是:Celery,RQ,APScheduler. Celery:非常强大的分布式任务调度框架 R ...
- 分布式定时任务框架——python定时任务框架APScheduler扩展
http://bbs.7boo.org/forum.php?mod=viewthread&tid=14546 如果将定时任务部署在一台服务器上,那么这个定时任务就是整个系统的单点,这台服务器出 ...
- python定时任务:apscheduler的使用(还有一个celery~)
文章摘自:https://www.cnblogs.com/luxiaojun/p/6567132.html 1 . 安装 pip install apscheduler 2 . 简单例子 # codi ...
随机推荐
- 标准 IO fprintf 与 sprintf 函数使用
函数原型 fprintf int fprintf(FILE *stream, const char *format, ...); 把数据写到流中 int sprintf(char *str, con ...
- java.sql.Date和java.util.Date的联系和区别
1) java.sql.Date是java.util.Date的子类,是一个包装了毫秒值的瘦包装器,允许 JDBC 将毫秒值标识为 SQL DATE 值.毫秒值表示自 1970 年 1 月 1 日 0 ...
- html标签注意事项
1,关于媒体的video标签 在同一个页面上如果有多个video标签,并且初始化都赋值,则video不会播放, 解决办法,用计时器每隔50ms给后面的video标签设置src,设置完为止 2,关于ch ...
- R语言 数据类型
R语言数据类型 通常,在使用任何编程语言进行编程时,您需要使用各种变量来存储各种信息. 变量只是保留值的存储位置. 这意味着,当你创建一个变量,你必须在内存中保留一些空间来存储它们. 您可能想存储各种 ...
- nc命令官方Demo实例
nc命令可用于发送任务tcp/udp连接和监听. 官方描述的主要功能包括: simple TCP proxies shell-script based HTTP clients and servers ...
- bash字符串前导美元符号的作用
problem bash内置变量IFS作为内部单词分隔符,其默认值为<space><tab><newline>, 我想设置它仅为\n,于是: OLD_IFS=$IF ...
- RHEL / CentOS Linux Install Core Development Tools Automake, Gcc (C/C++), Perl, Python & Debuggers
how do I install all developer tools such as GNU GCC C/C++ compilers, make and others, after install ...
- HDFS API 操作实例(二) 目录操作
1. 递归读取文件名 1.1 递归实现读取文件名(scala + listFiles) /** * 实现:listFiles方法 * 迭代列出文件夹下的文件,只能列出文件 * 通过fs的listFil ...
- IntelliJ IDEA(的springboot项目)环境准备(配置maven和jdk)
1.配置maven .使用自己电脑上装的maven版本,而非默认的.(方法一) (1)选择configure--Settings (2)搜索maven,配置3.6.2版本的maven.注意:将mave ...
- Codeforces 479【F】div3
题目链接:http://codeforces.com/problemset/problem/977/F 题意:给你一串数字序列,让你求最长上升子序列,但是这个子序列呢,它的数字得逐渐连续挨着. 题解: ...