This repository has been archived by the owner on Nov 30, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.py
89 lines (72 loc) · 2.14 KB
/
scheduler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from threading import Timer
from configObserver import ConfigObserver
import time, datetime
import bottle_helpers as bh
class Scheduler(object):
nextJob = []
timer = None
def __init__(self, config, tellstick):
self.config = config
self.jobs = config['jobs']
self.start()
self.tellstick = tellstick;
# Subscribe to changes in configs
class JobsWatcher(object):
def notify(subself, observable, key):
print "scheduler key changed"
self.start()
watcher = JobsWatcher()
config.observeKey('scheduler', watcher)
config.observeKey('jobs', watcher)
def stop(self):
if self.timer:
self.timer.cancel()
self.timer = None
def start(self):
self.stop()
self.calcAllRunTimes()
if self.config['scheduler']:
self.updateAndRunTimers()
def calcSoonestRunTime(self):
activeJobs = [
job['nextRunTime']
for job in self.jobs.itervalues()
if job['active'] == '1'
]
if len(activeJobs) == 0:
return None
return min(activeJobs)
def getJobsByRunTime(self, searchTime):
return [
job for job in self.jobs.itervalues()
if job['nextRunTime'] == searchTime
]
def updateAndRunTimers(self):
nowInEpoch = bh.dateTimeToEpoch(datetime.datetime.now())
if len(self.jobs) > 0:
soonestTime = self.calcSoonestRunTime()
if soonestTime:
self.nextJob = self.getJobsByRunTime(soonestTime)
timeToNextJob = soonestTime - nowInEpoch
if timeToNextJob <= 0:
print "FATAL ERROR: " + str(soonestTime) + " & " + str(nowInEpoch)
return
print "Next job scheduled for " + str(datetime.datetime.fromtimestamp(soonestTime))
self.timer = Timer(timeToNextJob, self.runCommand, ())
self.timer.start()
return
print "Scheduler has no jobs to run"
def runJob(self, job):
deviceId = int(job['deviceId'])
method = int(job['method'])
value = int(job['methodValue'])
print self.tellstick.device_command('', deviceId, value, method)
def runCommand(self):
if len(self.nextJob) > 0:
for job in self.nextJob:
self.runJob(job)
self.calcAllRunTimes()
self.updateAndRunTimers()
def calcAllRunTimes(self):
for id, job in self.jobs.iteritems():
bh.calcNextRunTime(job)