CrontabManager.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from crontab import CronTab
  2. from crontab import CronSlices
  3. from core.ConfigurationManager.BrainLoader import BrainLoader
  4. from core.Models import Event
  5. import logging
  6. class InvalidCrontabPeriod(Exception):
  7. pass
  8. CRONTAB_COMMENT = "JARVIS"
  9. class CrontabManager:
  10. def __init__(self, brain_file=None):
  11. self.my_user_cron = CronTab(user=True)
  12. self.base_command = "/path/to/jarvis/"
  13. self.brain = BrainLoader(filename=brain_file).get_brain()
  14. def load_events_in_crontab(self):
  15. """
  16. Remove all line in crontab with the CRONTAB_COMMENT
  17. Then add back line from event in the brain.yml
  18. :return:
  19. """
  20. # clean the current crontab from all jarvis event
  21. self._remove_all_jarvis_job()
  22. # load the brain file
  23. for synapse in self.brain.synapes:
  24. for signal in synapse.signals:
  25. # print signal
  26. # if the signal is an event we add it to the crontab
  27. if type(signal) == Event:
  28. # for all synapse with an event, we add the task id to the crontab
  29. self._add_event(period_string=signal.period, event_id=signal.identifier)
  30. def _add_event(self, period_string, event_id):
  31. my_user_cron = CronTab(user=True)
  32. job = my_user_cron.new(command=self.base_command+" "+str(event_id), comment=CRONTAB_COMMENT)
  33. if CronSlices.is_valid(period_string):
  34. job.setall(period_string)
  35. job.enable()
  36. else:
  37. raise InvalidCrontabPeriod("The crontab period %s is not valid" % period_string)
  38. # write the file
  39. my_user_cron.write()
  40. def get_jobs(self):
  41. return self.my_user_cron.find_comment(CRONTAB_COMMENT)
  42. def _remove_all_jarvis_job(self):
  43. """
  44. Remove all line in crontab that are attached to JARVIS
  45. :return:
  46. """
  47. iter = self.my_user_cron.find_comment(CRONTAB_COMMENT)
  48. for job in iter:
  49. logging.debug("remove job %s from crontab" % job)
  50. self.my_user_cron.remove(job)
  51. # write the file
  52. self.my_user_cron.write()
  53. # this is a fix for the CronTab lib
  54. # see https://github.com/peak6/python-crontab/issues/1
  55. new_iter = self.my_user_cron.find_comment(CRONTAB_COMMENT)
  56. sum_job = sum(1 for _ in new_iter)
  57. while sum_job > 0:
  58. self._remove_all_jarvis_job()