定时任务设置
一、Linux 设置定时任务crontab命令
示例如下:
crontab -e
# 进入定时任务编辑
0 6 * * * python3 predict.py >> /home/pi/logs/predict.log 2>&1
定时说明:
定时设置顺序分别为分、时、天、月、星期、命令。
星号(*):代表所有可能的值。
逗号(,):可以用逗号隔开的值指定一个列表范围,例如,“1,2,5,7,8,9”。
中杠(-):可以用整数之间的中杠表示一个整数范围,例如“2-6”表示“2,3,4,5,6”。
正斜线(/):例如*/10,如果用在minute字段,表示每十分钟执行一次。
注意问题:
当直接运行定时任务可能导致环境变量不生效,定时任务可能会运行失败,此时需要脚本运行方式。
首先编辑test.sh:
#!/bin/bash
source /etc/profile
/usr/bin/python3 /home/users/chenzhuo/program/tourist_predict/model/tourist_predict.py >> /home/users/chenzhuo/program/tourist_predict/predict.log 2>&1
再添加定时任务即可运行
0 6 * * * sh test.sh
如果代码中添加以下会使日志生效
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
二、Python定时任务框架apscheduler
主要不依赖于linux的crontab,也可应用于windows。
- 安装
pin install apscheduler
- 四大组件
触发器 triggers :用于设定触发任务的条件
任务储存器 job stores:用于存放任务,把任务存放在内存或数据库中
执行器 executors: 用于执行任务,可以设定执行模式为单线程或线程池
调度器 schedulers: 把上方三个组件作为参数,通过创建调度器实例来运行
调度器工作流程
from datetime import datetime
import os
from apscheduler.schedulers.blocking import BlockingScheduler
def tick():
print('Tick! The time is: %s' % datetime.now())
if __name__ == '__main__':
scheduler = BlockingScheduler()
scheduler.add_job(tick, 'interval', seconds=3)
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C '))
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass
首先实例化一个 BlockingScheduler 类,不带参数表明使用默认的作业存储器-内存,默认的执行器是线程池执行器,最大并发线程数默认为 10 个(另一个是进程池执行器)。
scheduler.add_job为添加作业,触发器为interval,周期;另外的触发器date 按特定时间点触发,cron 则按固定的时间间隔触发。
调度器类型:
BlockingScheduler:适用于调度程序是进程中唯一运行的进程,调用start函数会阻塞当前线程,不能立即返回。
BackgroundScheduler:适用于调度程序在应用程序的后台运行,调用start后主线程不会阻塞。
AsyncIOScheduler:适用于使用了asyncio模块的应用程序。
GeventScheduler:适用于使用gevent模块的应用程序。
TwistedScheduler:适用于构建Twisted的应用程序。
QtScheduler:适用于构建Qt的应用程序。
配置如下:
方法一:使用默认的作业存储器
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
def my_job(id='my_job'):
print(id, '-->', datetime.datetime.now())
jobstores = {
'default': MemoryJobStore()
}
executors = {
'default': ThreadPoolExecutor(20),
'processpool': ProcessPoolExecutor(10)
}
job_defaults = {
'coalesce': False,
'max_instances': 3
}
scheduler = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)
scheduler.add_job(my_job, args=['job_interval', ], id='job_interval', trigger='interval', seconds=5,
replace_existing=True)
scheduler.add_job(my_job, args=['job_cron', ], id='job_cron', trigger='cron', month='1-8,11-12', hour='0-18',
second='*/10', end_date = '2020-03-08')
scheduler.add_job(my_job, args=['job_once_now', ], id='job_once_now')
scheduler.add_job(my_job, args=['job_date_once', ], id='job_date_once', trigger='date', run_date='2020-03-02 17:10:05')
try:
scheduler.start()
except SystemExit:
print('exit')
exit()
方法二:使用数据库作为存储器
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
def my_job(id='my_job'):
print(id, '-->', datetime.datetime.now())
jobstores = {
'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
}
executors = {
'default': ThreadPoolExecutor(20),
'processpool': ProcessPoolExecutor(10)
}
job_defaults = {
'coalesce': False,
'max_instances': 3
}
scheduler = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)
scheduler.add_job(my_job, args=['job_interval', ], id='job_interval', trigger='interval', seconds=5,
replace_existing=True)
scheduler.add_job(my_job, args=['job_cron', ], id='job_cron', trigger='cron', month='1-8,11-12', hour='0-18',
second='*/10', end_date = '2020-05-30')
scheduler.add_job(my_job, args=['job_once_now', ], id='job_once_now')
scheduler.add_job(my_job, args=['job_date_once', ], id='job_date_once', trigger='date', run_date='2020-03-02 17:15:05')
try:
scheduler.start()
except SystemExit:
print('exit')
exit()
当程序运行后作业会被添加到数据库中,程序中断后会自动从数据库读取作业信息,可以注释掉scheduler.add_job的代码后者添加参数replace_existing=True。
使用参数misfire_grace_time设置错过运行的作业。
设置 coalesce=True 后,只会执行一次。
方法三:调度器事件监听
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()
在生产环境中,可以把出错信息换成发送一封邮件或者发送一个短信。
其他操作如下:
1 scheduler.remove_job(job_id,jobstore=None)#删除作业
2 scheduler.remove_all_jobs(jobstore=None)#删除所有作业
3 scheduler.pause_job(job_id,jobstore=None)#暂停作业
4 scheduler.resume_job(job_id,jobstore=None)#恢复作业
5 scheduler.modify_job(job_id, jobstore=None, **changes)#修改单个作业属性信息
6 scheduler.reschedule_job(job_id, jobstore=None, trigger=None,**trigger_args)#修改单个作业的触发器并更新下次运行时间
7 scheduler.print_jobs(jobstore=None, out=sys.stdout)#输出作业信息
三、python机器告警代码
以钉钉为例,添加机器人,拿到access_token,在workhood栏,
发送告警信息代码如下:
import os
import time
import requests
url = "https://oapi.dingtalk.com/robot/send?access_token=8e1c839e14c5c35a1fcb8bc894967ecb6229fbabb3197fb165f4e58575df7c96"
with os/popen('cat /home/chenz/update_keyword_title.log|grep "{}.*success"'.format(time.strftime("%Y-%m-%d"))) as p:
res = p.read()
if not res:
data = {
"msgtype": "text",
"text": {
"content": "大家好,我是ab"
},
}
r = requests.post(url, json=data)
更多信息请查看https://blog.csdn.net/somezz/article/details/83104368