怎么在Python中使用crontab模块清除定时任务

本篇文章给大家分享的是有关怎么在Python中使用crontab模块清除定时任务,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

centos7下安装Python的pip

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

No package python-pip availableError:Nothing to do

解决方法如下:

首先安装epel扩展源:

yum-yinstallepel-release

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

yum-yinstallpython-pip

安装完成之后清除cache:

yumcleanall

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

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

安装python定时任务模块:

pipinstallpython-crontab

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

[root@centos7mnt]#python
Python2.7.5(default,Jul132018,13:06:57)
[GCC4.8.520150623(RedHat4.8.5-28)]onlinux2
Type"help","copyright","credits"or"license"formoreinformation.
>>>importcrontab
>>>

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

#coding=utf-8
fromcrontabimportCronTab
classCrontab_Update(object):
def__init__(self):
#创建当前用户的crontab,当然也可以创建其他用户的,但得有足够权限
self.cron=CronTab(user=True)
#self.cron=CronTab(user='website')
defadd_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任务
defdel_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
importdatetime
#datetime.datetime.now().strftime("%Y-%m-%d%H:%M:%S")
withopen('/mnt/datetime_log.txt','a')asf:
f.write(datetime.datetime.now().strftime("%Y-%m-%d%H:%M:%S")+"\n")
f.close()

设置定时任务后:

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

crontab-l

结果如下:

怎么在Python中使用crontab模块清除定时任务

清除定时任务后:

怎么在Python中使用crontab模块清除定时任务

以上就是怎么在Python中使用crontab模块清除定时任务,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注恰卡编程网行业资讯频道。

发布于 2021-03-17 20:56:01
收藏
分享
海报
0 条评论
176
上一篇:NumPy模块怎么在Python3.5中使用 下一篇:如何在nodejs中使用async模块同步执行
目录

    推荐阅读

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码