CrontabManager.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from crontab import CronTab
  2. from crontab import CronSlices
  3. from core.ConfigurationManager.BrainLoader import BrainLoader
  4. from core.Models import Event
  5. class InvalidCrontabPeriod(Exception):
  6. pass
  7. CRONTAB_COMMENT = "JARVIS"
  8. class CrontabManager:
  9. def __init__(self, brain_file=None):
  10. self.my_user_cron = CronTab(user=True)
  11. self.base_command = "/path/to/jarvis/"
  12. self.brain = BrainLoader(filename=brain_file).get_brain()
  13. def load_events_in_crontab(self):
  14. # clean the current crontab from all jarvis event
  15. self._remove_all_jarvis_job()
  16. # # load the brain file
  17. for synapse in self.brain.synapes:
  18. for signal in synapse.signals:
  19. print signal
  20. # if it's an event we add it to the crontab
  21. if type(signal) == Event:
  22. print "is event"
  23. # for all tasks with an event, we add the task id to the crontab
  24. self._add_event(period_string=signal.period, event_id=signal.identifier)
  25. def _add_event(self, period_string, event_id):
  26. my_user_cron = CronTab(user=True)
  27. job = my_user_cron.new(command=self.base_command+" "+str(event_id), comment=CRONTAB_COMMENT)
  28. if CronSlices.is_valid(period_string):
  29. job.setall(period_string)
  30. job.enable()
  31. else:
  32. raise InvalidCrontabPeriod("The crontab period %s is not valid" % period_string)
  33. # write the file
  34. my_user_cron.write()
  35. def get_jobs(self):
  36. return self.my_user_cron.find_comment(CRONTAB_COMMENT)
  37. def _remove_all_jarvis_job(self):
  38. """
  39. Remove all line in crontab that are attached to JARVIS
  40. :return:
  41. """
  42. iter = self.my_user_cron.find_comment(CRONTAB_COMMENT)
  43. for job in iter:
  44. self.my_user_cron.remove(job)
  45. # write the file
  46. self.my_user_cron.write()