安装pip install python-crontab
#coding=utf-8
from crontab import CronTab
#创建类
class Crontabi(object):
def __init__(self):
self.cron = CronTab(user=True)
def add_crontab(self,cmmand_line,time_str,commont_name,user):
"""创建定时任务"""
job = self.cron.new(command=cmmand_line)
"""设置定时时间"""
job.setall(time_str)
"""给任务添加一个名称"""
job.set_comment(commont_name)
"""指定用户写入定时任务"""
self.cron.write_to_user(user=user)
def del_crontab(self,comment_name,user):
"""删除定时任务"""
self.cron.remove_all(comment=comment_name)
"""指定用户"""
self.cron.write_to_user(user=user)
#调用类
if __name__ == '__main__':
"""程序的路径"""
cmmand_line = "/usr/bin/python /backup-master/backup.py"
"""定时的时间"""
time_str = "%s %s * * %s" %(date[1],date[0],week)
"""定时任务的名称"""
commont_name = "exdata"
#指定用户
user = "root"
#创建对象
crontab_exdata=Crontabi()
crontab_exdata.add_crontab(cmmand_line,time_str,commont_name,user)