一、简单任务

定义一个函数,然后定义一个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. 【线段树】[Luogu P4198]楼房修建

    显然要维护斜率区间单调递增 并且第一个必选,后一个比前一个选中的斜率大的必选 考虑如何合并两个区间 我们维护一个least值,least这个值必选,且之后选的都必须严格大于least,Push_Up的 ...

  2. PushSharp 由于远程方已关闭传输流,身份验证失败。

    前段时间用到了PushSharp给APNS发推送,但是用的时候遇见很诡异的事情,每次第一次运行的时候能成功发送到 但是接下来就无限的提示“由于远程方已关闭传输流,身份验证失败. “ 然后我就各种找原因 ...

  3. Mycat搭建负载均衡,读写分离的Mysql集群

    Mycat搭建负载均衡,读写分离的Mysql集群 准备环境 1.mysql-5.7.24-linux-glibc2.12-x86_64.tar.gz 2.Mycat-server-1.6.7.4-te ...

  4. vue组件基础之父子传值

    可以看出数据从后端获取过来,最外层的父组件接收数据,子组件不能直接获取,必须由父组件传递,此时使用props,并且父组件的值更新后,子组件的值也会随之更新,但是反过来通过修改子组件props来影响父组 ...

  5. 47. List中特有的方法

    集合的体系:--------------| Collection  单列集合的根接口----------| List 如果实现了List接口的集合类,该类具备的特点是:有序,可重复---------- ...

  6. Jmeter-【JSON Extractor】-响应结果中一级key取值

    一.请求返回样式 二.取code值 三.查看结果

  7. JUC 一 CyclicBarrier 与 Semaphore

    java.util.concurrent CyclicBarrier简介 CyclicBarrier:可重用屏障/栅栏 类似于 CountDownLatch(倒计数闭锁),它能阻塞一组线程直到某个事件 ...

  8. thinkphp cookie支持

    系统内置了一个cookie函数用于支持和简化Cookie的相关操作,该函数可以完成Cookie的设置.获取.删除操作. Cookie设置 cookie('name','value'); //设置coo ...

  9. mac 安装配置使用 mongoldb

    mac 安装配置使用 mongoldb 安装和配置 brew install mongos brew install mongo # 密码就是用户的密码 # 配置数据文件 //如果不配置会出现错误62 ...

  10. CocoaPods更新2018年11月06日16:06:48

    https://gems.ruby-china.org点进去就知道了…… CocoaPods命令 更新 sudo gem install -n /usr/local/bin cocoapods --p ...