python操作crontab定时任务
生活随笔
收集整理的這篇文章主要介紹了
python操作crontab定时任务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python編程之定時任務(crontab)詳解
引言
python-crontab是python模塊,提供了對cron任務的訪問,并使得我們可以通過python對crontab文件進行修改。
安裝
pip install python-crontab注意:如果在使用CronTab的時候報錯,報錯信息為 got an unexpected keyword argument ‘user’ 可能是庫安裝錯了,應該安裝python-crontab而不是crontab。
import datetimefrom crontab import CronTabclass 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.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):"""新增定時任務"""# 創建任務job = self.cron.new(command=command)# 設置任務執行周期job.setall(time_str)# 注釋,也就是命令idjob.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')# 使用字符串變量作為crontabmem_cron = CronTab(tab="""* * * * * command""")def set_job_time(self):"""設置作業時間"""from crontab import CronTabcron = 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.commandcomment_name = job.commentdef 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)總結
以上是生活随笔為你收集整理的python操作crontab定时任务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 波士顿房价数据分析(R语言)
- 下一篇: 诺,你们要的Python进阶来咯!【函数