`
shaojiashuai123456
  • 浏览: 256711 次
  • 性别: Icon_minigender_1
  • 来自: 吉林
社区版块
存档分类
最新评论

python crontab使用

 
阅读更多
from crontab import CronTab
import os,sys

#crontab操作
class CrontabUpdate(object):
    def __init__(self, username='admin'):
        self._user = username
        # 创建当前用户的crontab,当然也可以创建其他用户的,但得有足够权限
        self.cron = CronTab(user=self._user)
  
    '''
    eg.
       cmmand_line : python /home/admin/test.py
       time_str : 1 * * * * 
       comment_name : TestCrontab
    '''
    def add_crontab(self, cmmand_line, time_str, comment_name):
        jobs = self.list_crontab()
        for job in jobs:
            if job.comment == comment_name:
                PrintErrorResult("[%s] had this crontab" % comment_name)
                return
        # 创建任务
        job = self.cron.new(command=cmmand_line)
        # 设置任务执行周期
        job.setall(time_str)
        # 给任务添加一个标识,给任务设置comment,这样就可以根据comment查询
        job.set_comment(comment_name)
        # 将crontab写入配置文件
        self.cron.write_to_user(user=self._user) # 指定用户,写入指定用户下的crontab任务

    def del_crontab(self, comment_name):
        self.cron.remove_all(comment=comment_name)
        # 写入配置文件
        self.cron.write_to_user(user=self._user) # 指定用户,删除指定用户下的crontab任务

    def del_all_crontab(self):
        #清空crontab
        self.cron.remove_all()
        self.cron.write_to_user(user=self._user)

    def list_crontab(self):  
        # 返回所有的定时任务,返回的是一个列表
        listCons = self.cron.crons
        return listCons

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics