一、简单任务

定义一个函数,然后定义一个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())

最新文章

  1. Servlet 服务器性能提高--->数据库请求频率控制(原创)
  2. 使用Gson转换json数据为Java对象的一个例子
  3. 如果客户端禁用cookie,session还能使用吗?
  4. Java多线程系列--“JUC集合”10之 ConcurrentLinkedQueue
  5. sql server 创建只读帐号
  6. C# 公历转农历
  7. Java统计数据库表中记录数
  8. 在fortran下进行openmp并行计算编程
  9. iOS富文本-NSAttributedString简单封装
  10. think straight系列读书笔记之《暗时间》
  11. bzoj 1187: [HNOI2007]神奇游乐园 插头dp
  12. stat~~~访问文件状态的利器
  13. Error (0xc0000225) installing Windows 8 R2 on VirtualBox
  14. 一个带动画的页面底部的TabBar的实现
  15. Tiny4412之蜂鸣器驱动与led灯驱动
  16. DIV+CSS初学随记
  17. 集合的遍历以及在Spring中的注入
  18. Win7 查看端口占用的进程,并根据进程id杀死进程。
  19. springboot:spring data jpa介绍
  20. Android 性能优化之内存泄漏检测以及内存优化(中)

热门文章

  1. Spring案例1出纯注解开机
  2. shell command to replace UltraEdit
  3. k8s 命令
  4. PHP 类中静态方法调用非静态方法
  5. Flink开发-IDEA scala开发环境搭建
  6. 记一次为解决Python读取PDF文件的Shell操作
  7. Java中的线程Thread方法之---stop()
  8. Matlab求三重积分
  9. PaperWeekly 第五期------从Word2Vec到FastText
  10. Windows内存管理(3)--检查内存可用性,结构化异常处理 和 ASSERT