image.png

    1. import logging
    2. from crontab import CronTab
    3. from datetime import datetime
    4. import json
    5. from utils.log import log
    6. from utils.jsonfile import JsonFile
    7. class CronOpt:
    8. #创建定时任务
    9. def __init__(self,user="root"):
    10. self.initialize(user)
    11. #初始化
    12. def initialize(self,user="root"):
    13. self.cron = CronTab(user)
    14. #查询列表
    15. def select(self,reInit = False):
    16. if reInit != False:
    17. # 强制重新读取列表
    18. self.initialize()
    19. cronArray = []
    20. for job in self.cron:
    21. # print job.command
    22. schedule = job.schedule(date_from=datetime.now())
    23. cronDict = {
    24. "job" : job,
    25. "task" : (job.command).replace(r'>/dev/null 2>&1', ''),
    26. "next" : str(schedule.get_next()),
    27. "prev" : str(schedule.get_prev()),
    28. "comment": job.comment
    29. }
    30. cronArray.append(cronDict)
    31. return cronArray
    32. #新增定时任务
    33. def add(self, command, timeStr, commentName):
    34. # 创建任务
    35. job = self.cron.new(command=command)
    36. # 设置任务执行周期
    37. job.setall(timeStr)
    38. # 备注,也是命令id
    39. job.set_comment(commentName)
    40. # 写入到定时任务
    41. self.cron.write()
    42. # 返回更新后的列表
    43. return self.select(True)
    44. #删除定时任务
    45. def delCron(self,commentName):
    46. # 创建任务
    47. for job in self.cron :
    48. if job.comment == commentName:
    49. self.cron.remove(job)
    50. self.cron.write()
    51. return self.select(True)
    52. #更新定时任务
    53. def update(self, command, timeStr, commentName):
    54. # 先删除任务
    55. self.delCron(commentName)
    56. # 再创建任务,以达到更新的结果
    57. return self.add(command, timeStr, commentName)
    58. def start(self):
    59. # c = CronOpt()
    60. # print(c.select())
    61. # # log.info(json.loads(c.select()))
    62. # # 新增定时任务
    63. # #print(c.add("ls /home","*/10 * * * *","测试"))
    64. # # 删除定时任务
    65. # # print(c.delCron("测试"))
    66. '''
    67. 思路:
    68. 读取配置文件
    69. 如果系统的定时任务中不存在配置文件中的定时任务id,则新增该定时任务
    70. 如果配置文件不存在系统中的定时任务id,则删除该任务
    71. '''
    72. c = CronOpt()
    73. jsonfile = JsonFile()
    74. contabjson = jsonfile.file_to_json("/home/zhanghui/script/lanhui/robot/mycrontab.json")
    75. crontabjsondict = {}
    76. for onecron in contabjson:
    77. crontabjsondict[onecron["commentName"]] = onecron
    78. selectdict = {}
    79. for oneselect in c.select():
    80. selectdict[oneselect["comment"]] = oneselect
    81. if oneselect["comment"] not in crontabjsondict and oneselect["comment"] != "":
    82. # print("删除定时任务")
    83. log.info("删除定时任务:"+str(c.delCron(oneselect["comment"])))
    84. for onecron in contabjson:
    85. if onecron["commentName"] not in selectdict:
    86. # print("增加定时任务")
    87. log.info("增加定时任务:"+str(c.add(onecron["command"],onecron["timeStr"], onecron["commentName"])))