python操作crontab定时任务
生活随笔
收集整理的這篇文章主要介紹了
python操作crontab定时任务
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Python編程之定時(shí)任務(wù)(crontab)詳解
引言
python-crontab是python模塊,提供了對(duì)cron任務(wù)的訪問,并使得我們可以通過python對(duì)crontab文件進(jìn)行修改。
安裝
pip install python-crontab注意:如果在使用CronTab的時(shí)候報(bào)錯(cuò),報(bào)錯(cuò)信息為 got an unexpected keyword argument ‘user’ 可能是庫安裝錯(cuò)了,應(yīng)該安裝python-crontab而不是crontab。
import datetimefrom crontab import CronTabclass TestCronClass:"""定時(shí)任務(wù)"""def __init__(self, user='root'):self.initialize(user)def initialize(self, user='root'):"""初始化"""self.cron = CronTab(user)def select(self, re_init=False):"""查詢定時(shí)任務(wù)列表"""if re_init:# 強(qiáng)制重新讀取列表self.initialize()cron_list = []for job in self.cron:# 打印job.commandschedule = 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_listdef add(self, command, time_str, comment_name):"""新增定時(shí)任務(wù)"""# 創(chuàng)建任務(wù)job = self.cron.new(command=command)# 設(shè)置任務(wù)執(zhí)行周期job.setall(time_str)# 注釋,也就是命令idjob.set_comment(comment_name)# 寫入到定時(shí)任務(wù)self.write()# 返回更新后的列表return self.select(True)def delete(self, comment_name):"""刪除定時(shí)任務(wù)"""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):"""刪除所有的任務(wù)"""self.cron.remove_all()self.cron.write()return self.select(True)def delete_multi(self, comment_name=None, command=None):"""刪除多個(gè)任務(wù),comment_name:注釋名/任務(wù)的命令示例: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):"""更新定時(shí)任務(wù)"""# 先刪除任務(wù)self.delete(comment_name)# 再創(chuàng)建任務(wù),以達(dá)到更新的結(jié)果return self.add(command, time_str, comment_name)def write(self):"""寫入任務(wù)"""# 1、把任務(wù)寫入系統(tǒng)self.cron.write()# # 2、把任務(wù)寫入文件# self.cron.write('filename.tab')# # 3、把任務(wù)寫入當(dāng)前用戶的定時(shí)任務(wù)中# self.cron.write_to_user(user=True)# # 4、把任務(wù)寫入特定用戶的定時(shí)任務(wù)中# self.cron.write_to_user(user='LoveFishO')def access_crontab(self):"""訪問crontab可以通過五種方式實(shí)現(xiàn)"""from crontab import CronTab# 下述三種方法只能在Unix上使用# 不會(huì)從任何用戶加載任何內(nèi)容empty_cron = CronTab()# 從當(dāng)前用戶加載my_user_cron = CronTab(user=True)# 從$username加載users_cron = CronTab(user='username')# 可適用于window# 從文件中加載file_cron = CronTab(tabfile='filename.tab')# 使用字符串變量作為crontabmem_cron = CronTab(tab="""* * * * * command""")def set_job_time(self):"""設(shè)置作業(yè)時(shí)間"""from crontab import CronTabcron = CronTab(user=True)job = cron.new(command='echo hello world')# 每兩分鐘運(yùn)行一次job.minute.every(2) # Set to */2 * * * *# 每兩小時(shí)運(yùn)行一次job.hour.every(2) # Set to * */2 * * *# 每兩天運(yùn)行一次job.day.every(2) # Set to * * */2 * *# 每天的早上2點(diǎn)執(zhí)行job.hour.on(2) # Set to * 2 * * *# 每周日?qǐng)?zhí)行job.dow.on('SUN')# 每周日、周五執(zhí)行job.dow.on('SUN', 'FRI')# 四月到11月期間執(zhí)行job.month.during('APR', 'NOV')# 每兩個(gè)月的2號(hào)到4號(hào)的早上10:02執(zhí)行job.setall(2, 10, '2-4', '*/2', None) # Set to 2 10 2-4 */2 *def get_job_command_or_comment(self, job):"""獲取任務(wù)的命令或注釋"""command = job.commandcomment_name = job.commentdef job_set_command_or_comment(self, job):"""修改任務(wù)的命令或注釋"""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)總結(jié)
以上是生活随笔為你收集整理的python操作crontab定时任务的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 波士顿房价数据分析(R语言)
- 下一篇: websocket python爬虫_p