-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduler.py
118 lines (92 loc) · 2.57 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
from logger import Logger
import schedule
import datetime
class Scheduler:
"""
Description
-----------
Takes care of setting up cron job.
Attributes
----------
cron
holds our CronTab instance.
schedule_tag_prefix
prefix we want to assign to all our jobs.
"""
def __init__(self):
"""
Description
-----------
Initializes our crontab instance.
"""
self.schedule = schedule
self.schedule_tag_prefix = 'job'
self.logger = Logger()
def run_daily(self, task: str):
"""
Descritpion
-----------
Sets up a daily cron job.
Parameters
----------
task : str
Script we want executed daily.
Returns
-------
self : Scheduler
Returns the scheduler instance.
"""
tag = f'{self.schedule_tag_prefix}_{datetime.datetime.now()}'
self.schedule.every().day.do(task).tag(tag)
self.logger.write(f'Run job {tag} daily.')
return self
def run_daily_at_time(self, task: str, time: str):
"""
Descritpion
-----------
Sets up a daily cron job.
Parameters
----------
task : str
Script we want executed daily.
time : str
Time of the day the script should run.
Returns
-------
self : Scheduler Instance
Returns the scheduler instance.
"""
tag = f'{self.schedule_tag_prefix}_{datetime.datetime.now()}'
self.schedule.every().day.at(time).do(task).tag(tag)
self.logger.write(f'Run job {tag} daily at {time} time')
return self
def start(self):
"""
Description
-----------
Begins the scheduled job.
Returns
-------
None
"""
while True:
self.logger.write('Starting up all jobs')
self.schedule.run_pending()
def clear_jobs(self, tag: str | bool = None):
"""
Description
-----------
Clears the job(s) with the given task else it clears all.
jobs
Parameters
----------
tag : str | bool
Tag identifier for a job.
Returns
-------
None
"""
self.logger.write(
'Clearing all jobs') if not tag else self.logger.write(
f'Clearing {tag} job')
self.schedule.clear(tag)