Ahenk/opt/ahenk/base/scheduler/custom/custom_scheduler.py

75 lines
2.5 KiB
Python
Raw Normal View History

2016-04-05 14:30:12 +03:00
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: İsmail BAŞARAN <ismail.basaran@tubitak.gov.tr> <basaran.ismaill@gmail.com>
from base.scheduler.base_scheduler import BaseScheduler
from base.Scope import Scope
2016-04-05 17:28:22 +03:00
from base.scheduler.custom.scheduledb import ScheduleTaskDB
from base.scheduler.custom.schedule_job import ScheduleTaskJob
2016-04-05 14:30:12 +03:00
from datetime import datetime, timedelta
import time
class CustomScheduler(BaseScheduler):
def __init__(self):
self.events = []
self.keep_run = True
self.logger = Scope.getInstance().getLogger()
2016-04-05 17:28:22 +03:00
self.scheduledb = ScheduleTaskDB()
2016-04-05 14:30:12 +03:00
def initialize(self):
2016-04-05 17:28:22 +03:00
self.scheduledb.initialize()
tasks = self.scheduledb.load()
2016-06-22 18:22:07 +03:00
if tasks:
for task in tasks:
self.add_job(ScheduleTaskJob(task))
2016-04-05 14:30:12 +03:00
2016-04-05 17:28:22 +03:00
def add_job(self, job):
2016-04-05 14:30:12 +03:00
self.events.append(job)
def save_and_add_job(self, task):
2016-06-22 18:22:07 +03:00
try:
self.logger.debug('[CustomScheduler] Saving scheduled task to database...')
self.scheduledb.save(task)
self.logger.debug('[CustomScheduler] Adding scheduled task to events...')
self.events.append(ScheduleTaskJob(task))
except Exception as e:
2016-08-10 12:36:17 +03:00
self.logger.error(
'[CustomScheduler] A problem occurred while saving and adding job. Error Message: {0}'.format(str(e)))
2016-06-22 18:22:07 +03:00
2016-08-10 12:36:17 +03:00
#unused
2016-06-22 18:22:07 +03:00
def remove_job(self, task_id):
for event in self.events:
2016-06-22 18:22:07 +03:00
if event.task.get_id() == task_id:
self.scheduledb.delete(task_id)
self.logger.debug('[CustomScheduler] Task was deleted from scheduled tasks table')
self.events.remove(event)
2016-06-22 18:22:07 +03:00
self.logger.debug('[CustomScheduler] Task was removed from events')
2016-08-10 12:36:17 +03:00
# unused
def remove_job_via_task_id(self, task_id):
for event in self.events:
2016-06-22 18:22:07 +03:00
if event.task.get_id() == task_id:
self.scheduledb.delete(event.task)
self.events.remove(event)
2016-04-05 14:30:12 +03:00
def stop(self):
self.keep_run = False
def list_schedule_tasks(self):
return self.scheduledb.load()
2016-04-05 14:30:12 +03:00
def run(self):
t = datetime(*datetime.now().timetuple()[:5])
2016-08-10 12:36:17 +03:00
while 1 and self.keep_run:
if self.events is not None and len(self.events) > 0:
2016-04-05 14:30:12 +03:00
2016-08-10 12:36:17 +03:00
for e in self.events:
e.check(t)
2016-04-05 14:30:12 +03:00
2016-08-10 12:36:17 +03:00
t += timedelta(minutes=1)
if datetime.now() < t:
sl = (t - datetime.now()).seconds
time.sleep(sl)