Python编程之定时任务(crontab)详解
引言
python-crontab是python模块,提供了对cron任务的访问,并使得我们可以通过python对crontab文件进行修改。
环境
- ubuntu18.04
安装
pip install python-crontab
注意:如果在使用CronTab的时候报错,报错信息为 got an unexpected keyword argument ‘user’ 可能是库安装错了,应该安装python-crontab而不是crontab。
import datetime
from crontab import CronTab
class TestCronClass:
"""定时任务"""
def __init__(self, user='root'):
self.initialize(user)
def initialize(self, user='root'):
"""初始化"""
self.cron = CronTab(user)
def select(self, re_init=False):
"""查询定时任务列表"""
if re_init:
# 强制重新读取列表
self.initialize()
cron_list = []
for job in self.cron:
# 打印job.command
schedule = job.schedule(date_from=datetime.datetime.now())
cron_dict = {
'task': (job.command).replace(r'>/dev/null 2>&1', ''),
'next': str(schedule.get_next()),
'prev': str(schedule.get_prev()),
'comment': job.comment,
}
cron_list.append(cron_dict)
return cron_list
def add(self, command, time_str, comment_name):
"""新增定时任务"""
# 创建任务
job = self.cron.new(command=command)
# 设置任务执行周期
job.setall(time_str)
# 注释,也就是命令id
job.set_comment(comment_name)
# 写入到定时任务
self.write()
# 返回更新后的列表
return self.select(True)
def delete(self, comment_name):
"""删除定时任务"""
for job in self.cron:
if job.comment == comment_name:
self.cron.remove(job)
self.cron.write()
return self.select(True)
def delete_all(self):
"""删除所有的任务"""
self.cron.remove_all()
self.cron.write()
return self.select(True)
def delete_multi(self, comment_name=None, command=None):
"""
删除多个任务,comment_name:注释名/任务的命令
示例:
cron.remove_all(comment='LoveFishO')
cron.remove_all('echo')
"""
if comment_name:
self.cron.remove_all(comment=comment_name)
elif command:
self.cron.remove_all(command)
self.cron.write()
return self.select(True)
def update(self, command, time_str, comment_name):
"""更新定时任务"""
# 先删除任务
self.delete(comment_name)
# 再创建任务,以达到更新的结果
return self.add(command, time_str, comment_name)
def write(self):
"""写入任务"""
# 1、把任务写入系统
self.cron.write()
# # 2、把任务写入文件
# self.cron.write('filename.tab')
# # 3、把任务写入当前用户的定时任务中
# self.cron.write_to_user(user=True)
# # 4、把任务写入特定用户的定时任务中
# self.cron.write_to_user(user='LoveFishO')
def access_crontab(self):
"""访问crontab可以通过五种方式实现"""
from crontab import CronTab
# 下述三种方法只能在Unix上使用
# 不会从任何用户加载任何内容
empty_cron = CronTab()
# 从当前用户加载
my_user_cron = CronTab(user=True)
# 从$username加载
users_cron = CronTab(user='username')
# 可适用于window
# 从文件中加载
file_cron = CronTab(tabfile='filename.tab')
# 使用字符串变量作为crontab
mem_cron = CronTab(tab="""* * * * * command""")
def set_job_time(self):
"""设置作业时间"""
from crontab import CronTab
cron = CronTab(user=True)
job = cron.new(command='echo hello world')
# 每两分钟运行一次
job.minute.every(2) # Set to */2 * * * *
# 每两小时运行一次
job.hour.every(2) # Set to * */2 * * *
# 每两天运行一次
job.day.every(2) # Set to * * */2 * *
# 每天的早上2点执行
job.hour.on(2) # Set to * 2 * * *
# 每周日执行
job.dow.on('SUN')
# 每周日、周五执行
job.dow.on('SUN', 'FRI')
# 四月到11月期间执行
job.month.during('APR', 'NOV')
# 每两个月的2号到4号的早上10:02执行
job.setall(2, 10, '2-4', '*/2', None) # Set to 2 10 2-4 */2 *
def get_job_command_or_comment(self, job):
"""获取任务的命令或注释"""
command = job.command
comment_name = job.comment
def job_set_command_or_comment(self, job):
"""修改任务的命令或注释"""
job.set_command("echo LoveFishO")
job.set_comment("LoveFishO")
if __name__ == '__main__':
c = TestCronClass()
comment = "test_python_cron"
c.add("ls /home", "*/10 * * * *", comment)
# c.delete(comment)