123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- import os
- from crontab import CronTab
- class Control:
- @classmethod
- def crontab_add(cls, rule, command):
- """
- 添加 crontab 任务
- :param rule: 运行时间规则,如:* * * * *;00 00 * * *
- :param command: crontab 任务,如:"python3 control/monitor/monitor_logs.py"
- :return:None
- """
-
- cron = CronTab(user=True)
-
- job = cron.new(command=command)
- job.setall(rule)
-
- cron.write()
- @classmethod
- def crontab_edit(cls, enable, command):
- """
- 注释 / 取消注释 crontab 任务
- :param enable: True:取消注释 crontab 任务;False:注释 crontab 任务
- :param command: 需要注释的 crontab 任务,如:"python3 control/monitor/monitor_logs.py"
- :return: None
- """
-
- cron = CronTab(user=True)
-
-
- job = next(cron.find_command(command))
-
- job.enable(enable)
-
- cron.write()
- @classmethod
- def crontab_remove(cls, command):
- """
- 删除 crontab 任务
- :param command: crontab 任务,如:"python3 control/monitor/monitor_logs.py"
- :return:
- """
-
- cron = CronTab(user=True)
-
- job = cron.find_command(command)
-
- cron.remove(job)
-
- cron.write()
- @classmethod
- def crawler_stop(cls, command):
- cmd = f"ps aux | grep {command.split(' ')[-1].split('/')[-1]}" + " | grep -v grep | awk '{print $2}' | xargs kill -9"
- print(cmd)
- print("执行杀进程命令")
- os.system(cmd)
-
- cron = CronTab(user=True)
- if command in [job.command for job in cron]:
- print("command已存在,开始停用\n")
- cls.crontab_edit(False, command)
- return
- else:
- print("command不存在,无需停用\n")
- return
- @classmethod
- def crawler_start(cls, rule, command):
-
- cron = CronTab(user=True)
- if command in [job.command for job in cron]:
- print("command 已存在,开始启用\n")
- cls.crontab_edit(True, command)
- return
- else:
- print("command 不存在,新增并启用\n")
- cls.crontab_add(rule, command)
- return
- @classmethod
- def crawler_restart(cls, rule, command):
- cmd = f"ps aux | grep {command.split(' ')[-1].split('/')[-1]}" + " | grep -v grep | awk '{print $2}' | xargs kill -9"
- print(cmd)
- print("执行杀进程命令")
- os.system(cmd)
- print("正在启动 command")
- cls.crawler_start(rule, command)
- if __name__ == "__main__":
-
-
-
-
-
-
- Control.crawler_restart("* * * * *", "python3 control/monitor/monitor_logs.py")
- pass
|