CrontabManager.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. from crontab import CronTab
  2. from crontab import CronSlices
  3. class InvalidCrontabPeriod(Exception):
  4. pass
  5. CRONTAB_COMMENT = "JARVIS"
  6. class CrontabManager:
  7. def __init__(self, brain_file=None):
  8. self.my_user_cron = CronTab(user=True)
  9. self.base_command = "/usr/bin/echo"
  10. def load_events_in_crontab(self):
  11. # clean the current crontab from all jarvis event
  12. self._remove_all_jarvis_job()
  13. # # load the brain file
  14. period_string = "* * 5 5 *"
  15. event_id = 1
  16. # for all tasks with an event, we add the task id to the crontab
  17. self._add_event(period_string=period_string, event_id=event_id)
  18. def _add_event(self, period_string, event_id):
  19. my_user_cron = CronTab(user=True)
  20. job = my_user_cron.new(command=self.base_command, comment=CRONTAB_COMMENT)
  21. if CronSlices.is_valid(period_string):
  22. job.setall(period_string)
  23. job.enable()
  24. else:
  25. raise InvalidCrontabPeriod("The crontab period %s is not valid" % period_string)
  26. # write the file
  27. my_user_cron.write()
  28. def get_jobs(self):
  29. return self.my_user_cron.find_comment(CRONTAB_COMMENT)
  30. def _remove_all_jarvis_job(self):
  31. """
  32. Remove all line in crontab that are attached to JARVIS
  33. :return:
  34. """
  35. iter = self.my_user_cron.find_comment(CRONTAB_COMMENT)
  36. for job in iter:
  37. self.my_user_cron.remove(job)
  38. # write the file
  39. self.my_user_cron.write()