zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python - python crontab模块设置和清除定时任务

Python模块 设置 任务 定时 清除 crontab
2023-09-27 14:29:10 时间

centos7下安装Python的pip

root用户使用yum install -y python-pip 时会报如下错误:

No package python-pip available

Error:Nothing to do

 

解决方法如下:

  首先安装epel扩展源:

yum -y install epel-release

 

更新完成之后,就可安装pip:

  

yum -y install python-pip

      

安装完成之后清除cache:

  

yum clean all

这是在root用户时使用的命令,当前用户如果不具有root权限,加上sudo。

在其他Linux类似centos衍生的发行版也可以用此方法解决。

安装python定时任务模块:

pip install python-crontab

安装成功:可成功import 该模块

[root@centos7 mnt]# python
Python 2.7.5 (default, Jul 13 2018, 13:06:57) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import crontab
>>>

封装一个类,用来新增和清除定时任务:

# coding=utf-8
from crontab import CronTab

class Crontab_Update(object):

    def __init__(self):
        # 创建当前用户的crontab,当然也可以创建其他用户的,但得有足够权限
        self.cron = CronTab(user=True)
        # self.cron = CronTab(user='website')

    def add_crontab_job(self, cmmand_line, time_str, commont_name, user):
        # 创建任务
        job = self.cron.new(command=cmmand_line)
        # 设置任务执行周期
        job.setall(time_str)
        # 给任务添加一个标识,给任务设置comment,这样就可以根据comment查询
        job.set_comment(commont_name)
        # 将crontab写入配置文件
        # self.cron.write()
        self.cron.write_to_user(user=user)  # 指定用户,写入指定用户下的crontab任务

    def del_crontab_jobs(self, comment_name, user):
        # 根据comment查询,当时返回值是一个生成器对象,
        # 不能直接根据返回值判断任务是否存在,
        # 如果只是判断任务是否存在,可直接遍历my_user_cron.crons
        # jobs = self.cron.find_comment(commont_name)

        # 返回所有的定时任务,返回的是一个列表
        # a = self.cron.crons
        # print 'a = ', a
        # print 'len(a) = ', len(a)

        # 按comment清除定时任务
        # self.cron.remove_all(comment=comment_name)

        # 按comment清除多个定时任务,一次write即可
        self.cron.remove_all(comment=comment_name)
        self.cron.remove_all(comment=comment_name+ ' =')

        # 清除所有定时任务
        # self.cron.remove_all()

        # 写入配置文件
        # self.cron.write()
        self.cron.write_to_user(user=user)  # 指定用户,删除指定用户下的crontab任务

if __name__ == "__main__":
    print 'start --------'
    cmmand_line = "/usr/bin/python /mnt/print_time.py"
    time_str = "* * * * *"
    commont_name = "Test_Crontab_Job"
    user = "xue"
    # 创建一个实例
    crontab_update = Crontab_Update()

    # 调用函数新增一个crontab任务
    # print '&&&&&& add_crontab_job '
    # crontab_update.add_crontab_job(cmmand_line, time_str, commont_name, user)

    print '&&&&&& del_crontab_jobs '
    crontab_update.del_crontab_jobs(commont_name, user)
    print 'end -------'

定时任务执行的python脚本如下:print_time.py

# coding=utf-8
import datetime

# datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

with open('/mnt/datetime_log.txt', 'a') as f:
	f.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+"\n")
f.close()

设置定时任务后:

下面可通过命令查看,是否创建成功:

crontab -l

结果如下:

清除定时任务后:

 

还有一些功能没有完全介绍,大家可以参考官方文档https://pypi.python.org/pypi/python-crontab