python操作crontab定时任务

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)

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
在Linux系统中,可以使用crontab来设置定时任务。通过引用的信息,我们可以了解到在设置定时任务时,可以使用"crontab -e"命令来添加任务,并且可以指定脚本的解释器为"/usr/local/bin/python"。此外,我们还可以看到在设置定时任务时,需要注意全局变量的使用,确保使用正确的Python版本。 在设置crontab定时任务中使用pymysql时,可以按照以下步骤操作: 1. 首先,确认已经在服务器上安装了pymysql模块,可以使用"pip install pymysql"命令来安装。 2. 确认pymysql模块的安装位置,可以使用命令"pip show pymysql"来查看安装路径。注意,如果安装路径不是"/usr/bin/python",而是"/usr/local/bin/python",则需要将定时任务的解释器设定为"/usr/local/bin/python"。 3. 编辑crontab定时任务,使用"crontab -e"命令,在文件中添加定时任务,并指定解释器为正确的路径。 4. 保存并退出文件,定时任务将会按照设定的时间周期执行,并使用指定的解释器运行脚本。 综上所述,通过以上步骤,你可以在crontab定时任务中使用pymysql模块。请注意在设置定时任务时,确保全局变量的使用正确,并指定正确的Python解释器路径。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [利用Linux的crontab实现python定时任务](https://blog.csdn.net/weixin_40238625/article/details/78992506)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [SMZDM_Monitor:什么值得买网站的定时监测工具](https://download.csdn.net/download/weixin_42127020/18619953)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值