class CronTabs(list): """Singleton dictionary of all detectable crontabs""" _all = None _self = None def __new__(cls, *args, **kw): if not cls._self: cls._self = super(CronTabs, cls).__new__(cls, *args, **kw) return cls._self def __init__(self): if not self: for loc in KNOWN_LOCATIONS: self.add(*loc) def add(self, cls, *args): for tab in cls(*args, tabs=self): self.append(tab) self._all = None @property def all(self): """Return a CronTab object with all jobs (read-only)""" if self._all is None: self._all = CronTab(user=False) for tab in self: for job in tab: if job.user is None: job.user = tab.user or 'unknown' self._all.append(job) return self._all
def cron_write(schedule): cron = CronTab(user=True) new_cron = CronTab() # NOTE: remove* 系のメソッドを使うとどんどん空行が増えるので, # append して更新を行う. for job in cron: for mode in ['open', 'close']: if re.compile('{} \({}\)'.format(re.escape(SCHEDULE_MARKER), mode)).search(job.comment): job = cron_create_job(cron, schedule, mode) schedule[mode]['append'] = True # NOTE: Ubuntu の場合 apt でインストールした python-crontab # では動かない.pip3 でインストールした python-crontab が必要. new_cron.append(job) for mode in ['open', 'close']: if ('append' not in schedule[mode]): new_cron.append(cron_create_job(cron, schedule, mode)) new_cron.write_to_user(user=True) # すぐに反映されるよう,明示的にリロード subprocess.check_call(['sudo', '/etc/init.d/cron', 'restart'])
def add_job(job): root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) command = '. /etc/profile; cd {}; export PYTHONPATH=$PYTHONPATH:{}; python3 app/job_runner.py --job_name "{}" >> /tmp/schedule_jobs.log 2>&1'.format( root_path, root_path, job['name']) job_string = job_to_string(job=job, command=command) cron = CronTab(user=USERNAME) item = CronItem.from_line(job_string, cron=cron) cron.append(item) cron.write()
def schedule_cron(command, interval, crontab=None): from crontab import CronTab, CronItem if not os.path.exists(crontab): with open(crontab, 'w'): pass if crontab: c = CronTab(tabfile=crontab) else: c = CronTab(user=getpass.getuser()) job = CronItem.from_line(interval + ' ' + command, cron=c) c.append(job) c.write() return c, job