nuts-scheduler 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nuts/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .worker import Worker
2
+ from .job import NutsJob
3
+ from .cron import Cron
4
+
nuts/cron.py ADDED
@@ -0,0 +1,216 @@
1
+ import datetime
2
+ from dateutil.relativedelta import relativedelta
3
+ import calendar
4
+
5
+
6
+ class Cron():
7
+
8
+ def __get_start_frequency(self, input: str, base: str = None) -> list[str]:
9
+ try:
10
+ [start, frequency] = input.split('/')
11
+ if start == '*':
12
+ start = base if base is not None else '0'
13
+ return [int(start), int(frequency)]
14
+
15
+ except Exception:
16
+ raise Exception(f'Invalid expression {input}: Valid examples include: */int, int/int')
17
+
18
+ def __get_week_structure(self, year: int, month: int) -> list[int]:
19
+ start_of_month = calendar.monthrange(year, month)[0].value
20
+ week_structure = []
21
+ while len(week_structure) < 7:
22
+ if start_of_month < 8:
23
+ week_structure.append(start_of_month)
24
+ start_of_month += 1
25
+ else:
26
+ start_of_month = 1
27
+ return week_structure
28
+
29
+ def get_next_execution(self, schedule: str, now: datetime.datetime = datetime.datetime.now(datetime.timezone.utc)) -> int:
30
+ try:
31
+ [seconds, minutes, hours, day_of_week, month, day_of_month, year] = schedule.split(' ')
32
+ except Exception:
33
+ raise Exception('Expression must have 7 postions')
34
+
35
+ if '?' not in [day_of_week, day_of_month]:
36
+ raise Exception('Cannot specify both day-of-week and day-of-month')
37
+
38
+ [next_seconds, inc_minute] = self.parse_seconds(seconds, now)
39
+ if inc_minute:
40
+ now = now + datetime.timedelta(minutes=1)
41
+ [next_minutes, inc_hour] = self.parse_minutes(minutes, now)
42
+ if inc_hour:
43
+ now = now + datetime.timedelta(hours=1)
44
+ [next_hours, inc_day] = self.parse_hours(hours, now)
45
+ if inc_day:
46
+ now = now + datetime.timedelta(days=1)
47
+ if day_of_week == '?':
48
+ [next_days, inc_month] = self.parse_day_of_month(day_of_month, now)
49
+
50
+ else:
51
+ [next_days, inc_month] = self.parse_day_of_week(day_of_week, now)
52
+
53
+ if inc_month:
54
+ now = now + relativedelta(months=1)
55
+ [next_months, inc_year] = self.parse_months(month, now)
56
+ if inc_year:
57
+ now = now + relativedelta(years=1)
58
+
59
+ [next_year, _] = self.parse_years(year, now)
60
+ res = datetime.datetime(next_year, next_months, next_days, next_hours, next_minutes, next_seconds, tzinfo=datetime.timezone.utc)
61
+
62
+ return res
63
+
64
+ def parse_seconds(self, seconds: str, now: datetime.datetime) -> list[int, bool]:
65
+ if seconds == '*':
66
+ seconds = '0/1'
67
+
68
+ if '/' not in seconds:
69
+ start = int(seconds)
70
+ frequency = 60
71
+ else:
72
+ [start, frequency] = self.__get_start_frequency(seconds)
73
+
74
+ upcoming = [i for i in range(start, 60, frequency) if i > now.second]
75
+ try:
76
+ return [upcoming[0], False]
77
+ except Exception:
78
+ return [start, True]
79
+
80
+ def parse_minutes(self, minutes: str, now: datetime.datetime) -> list[int, False]:
81
+ if minutes == '*':
82
+ minutes = '0/1'
83
+
84
+ if '/' not in minutes:
85
+ start = int(minutes)
86
+ frequency = 60
87
+ else:
88
+ [start, frequency] = self.__get_start_frequency(minutes)
89
+
90
+ upcoming = [i for i in range(start, 60, frequency) if i >= now.minute]
91
+ try:
92
+ return [upcoming[0], False]
93
+ except Exception:
94
+ return [start, True]
95
+
96
+ def parse_hours(self, hours: str, now: datetime.datetime) -> list[int, bool]:
97
+ if hours == '*':
98
+ hours = '0/1'
99
+
100
+ if '/' not in hours:
101
+ start = int(hours)
102
+ frequency = 24
103
+ else:
104
+ [start, frequency] = self.__get_start_frequency(hours)
105
+
106
+ upcoming = [i for i in range(start, 24, frequency) if i >= now.hour]
107
+ try:
108
+ return [upcoming[0], False]
109
+ except Exception:
110
+ return [start, True]
111
+
112
+ def parse_day_of_month(self, days: str, now: datetime.datetime) -> list[int, bool]:
113
+ end_of_month = calendar.monthrange(now.year, now.month)[1]
114
+ if days == '*':
115
+ days = '1/1'
116
+ if '/' not in days:
117
+ start = int(days)
118
+ frequency = end_of_month
119
+ else:
120
+ [start, frequency] = self.__get_start_frequency(days, '1')
121
+
122
+ upcoming = [i for i in range(start, end_of_month + 1, frequency) if i >= now.day]
123
+ try:
124
+ return [upcoming[0], False]
125
+ except Exception:
126
+ return [start, True]
127
+
128
+ def __get_upcoming_weekdays(self, days: str, week_structure: list[int], now: datetime.datetime, frequency: int = None) -> list[int]:
129
+ end_of_month = calendar.monthrange(now.year, now.month)[1] + 1
130
+ month_days = list(range(1, end_of_month))
131
+ weeks = [month_days[i * 7:(i+1) * 7] for i in range((len(month_days) + 7 - 1) // 7)]
132
+ dow_idx = week_structure.index(int(days))
133
+
134
+ upcoming = []
135
+
136
+ if frequency:
137
+ start = weeks[0][dow_idx]
138
+ upcoming = [i for i in range(start, end_of_month, frequency) if i >= now.day]
139
+ else:
140
+ for w in weeks:
141
+ try:
142
+ d = w[dow_idx]
143
+ if d >= now.day:
144
+ upcoming.append(d)
145
+ except Exception:
146
+ pass
147
+ return upcoming
148
+
149
+ def parse_day_of_week(self, days: str, now: datetime.datetime) -> int:
150
+ week_structure = self.__get_week_structure(now.year, now.month)
151
+ if days == '*':
152
+ days = f'{week_structure[0]}/1'
153
+
154
+ if '/' not in days:
155
+ start = int(days)
156
+
157
+ upcoming = self.__get_upcoming_weekdays(start, week_structure, now)
158
+ try:
159
+ return [upcoming[0], False]
160
+ except Exception:
161
+ # Need to shift forward to the next month
162
+ next_month = now + datetime.timedelta(days=calendar.monthrange(now.year, now.month)[1] - now.day + 1)
163
+ week_structure = self.__get_week_structure(next_month.year, next_month.month)
164
+ upcoming = self.__get_upcoming_weekdays(start, week_structure, next_month)
165
+
166
+ return [upcoming[0], True]
167
+
168
+ else:
169
+ [start, frequency] = self.__get_start_frequency(days, '1')
170
+ upcoming = self.__get_upcoming_weekdays(start, week_structure, now, frequency)
171
+ try:
172
+ return [upcoming[0], False]
173
+ except Exception:
174
+ # Need to shift forward to the next month
175
+ now = now + datetime.timedelta(days=calendar.monthrange(now.year, now.month)[1] - now.day + 1)
176
+ week_structure = self.__get_week_structure(now.year, now.month)
177
+ upcoming = self.__get_upcoming_weekdays(start, week_structure, now, frequency)
178
+
179
+ return [upcoming[0], True]
180
+
181
+ def parse_months(self, months: str, now: datetime.datetime) -> int:
182
+ if months == '*':
183
+ months = '1/1'
184
+
185
+ if '/' not in months:
186
+ start = int(months)
187
+ frequency = 12
188
+ else:
189
+ [start, frequency] = self.__get_start_frequency(months, '1')
190
+
191
+ upcoming = [i for i in range(start, 13, frequency) if i >= now.month]
192
+ try:
193
+ return [upcoming[0], False]
194
+ except Exception:
195
+ return [start, True]
196
+
197
+ def parse_years(self, years: str, now: datetime.datetime) -> int:
198
+ if years == '*':
199
+ years = '1970/1'
200
+
201
+ if '/' not in years:
202
+ start = int(years)
203
+ frequency = 1
204
+ else:
205
+ [start, frequency] = self.__get_start_frequency(years, '1970')
206
+
207
+ upcoming = [i for i in range(start, now.year + frequency, frequency) if i >= now.year]
208
+ try:
209
+ return [upcoming[0], False]
210
+ except Exception:
211
+ return [start, True]
212
+
213
+
214
+ if __name__ == '__main__':
215
+ cron = Cron()
216
+ cron.get_next_execution('2/4 * * * * ? *')
nuts/job.py ADDED
@@ -0,0 +1,19 @@
1
+ from typing import Union, Any
2
+
3
+
4
+ class NutsJob():
5
+ '''
6
+ A Nuts Job
7
+ '''
8
+ name: str
9
+ schedule: Union[str, None]
10
+ success: bool
11
+ result: Any
12
+ error: Exception
13
+
14
+ def __init__(self):
15
+ self.name = None
16
+ self.schedule = None
17
+ self.success = False
18
+ self.result = None
19
+ self.error = None
nuts/worker.py ADDED
@@ -0,0 +1,174 @@
1
+ import os
2
+ import json
3
+ from redis import Redis
4
+ from .job import NutsJob
5
+ from .cron import Cron
6
+ import datetime
7
+ import logging
8
+
9
+
10
+ class Worker():
11
+ '''
12
+ A NUTS worker
13
+ '''
14
+ id: int
15
+ redis: Redis
16
+ scheduler: Cron
17
+ logger: logging.Logger
18
+ jobs: list[NutsJob]
19
+ kwargs: dict[str, any]
20
+ scheduled_queue: str
21
+ pending_queue: str
22
+ completed_queue: str
23
+ last_run: datetime.datetime
24
+ running_list: str
25
+
26
+ def __init__(self, redis: Redis, jobs: list[NutsJob], **kwargs):
27
+ self.id = os.getpid()
28
+ self.scheduled_queue = 'nuts|jobs|scheduled'
29
+ self.running_list = 'nuts|job|running'
30
+ self.pending_queue = 'nuts|jobs|pending'
31
+ self.completed_queue = 'nuts|jobs|completed'
32
+ self.kwargs = kwargs
33
+
34
+ self.last_run = datetime.datetime.fromtimestamp(0)
35
+
36
+ self.redis = redis
37
+
38
+ self.scheduler = Cron()
39
+
40
+ self.logger = logging.getLogger(f'worker|{self.id}')
41
+
42
+ self.jobs = []
43
+
44
+ logging.basicConfig(level=logging.INFO)
45
+
46
+ is_leader = self.check_leader()
47
+ if is_leader:
48
+ self.logger.info(f'Worker {self.id} assuming leadership')
49
+
50
+ for job in jobs:
51
+ j = job.Job()
52
+
53
+ self.jobs.append(j)
54
+
55
+ if is_leader and j.schedule:
56
+ self.logger.info(f'Registering Cron Job {j.name}')
57
+
58
+ next_execution = self.scheduler.get_next_execution(j.schedule).timestamp()
59
+ scheduled_job = False
60
+ running_job = None
61
+ try:
62
+ pending = self.redis.zscan('nuts|jobs|pending', match=j.name)
63
+ if pending[1][0]:
64
+ if pending[1][1] != next_execution:
65
+ # Schedule has changed
66
+ self.redis.zrem(self.scheduled_queue, job.name)
67
+ self.redis.zadd(self.scheduled_queue, {job.name: next_execution})
68
+ else:
69
+ scheduled_job = True
70
+
71
+ except Exception:
72
+ pass
73
+
74
+ running_job = self.redis.hget(self.running_list, j.name)
75
+
76
+ if not scheduled_job and not running_job:
77
+ self.redis.zadd(self.pending_queue, {j.name: next_execution})
78
+
79
+ def check_leader(self) -> bool:
80
+ is_leader = False
81
+ leadership_check = self.redis.setnx('leader_id', self.id)
82
+
83
+ if not leadership_check:
84
+ leader_id = self.redis.get('leader_id')
85
+ if leader_id == self.id:
86
+ self.redis.expire('leader_id', 600)
87
+
88
+ is_leader = True
89
+
90
+ else:
91
+ self.redis.expire('leader_id', 600)
92
+ is_leader = True
93
+
94
+ return is_leader
95
+
96
+ def schedule_pending_job(self, job_name):
97
+ self.redis.sadd(self.pending_queue, json.dumps([job_name, []]))
98
+
99
+ def move_scheduled_to_pending(self):
100
+ now = round(datetime.datetime.now(datetime.timezone.utc).timestamp())
101
+ start = round(self.last_run.timestamp())
102
+ ready_jobs = self.redis.zrange(self.scheduled_queue, start=start, end=now, withscores=True)
103
+
104
+ if len(ready_jobs) > 0:
105
+ latest = max(j[0] for j in ready_jobs)
106
+ self.redis.zremrangebyscore(self.scheduled_queue, min=self.last_run.timestamp(), max=latest)
107
+
108
+ for job in ready_jobs:
109
+ self.schedule_pending_job(job[0])
110
+
111
+ def move_pending_to_running(self, job: NutsJob, job_args: list):
112
+ now = datetime.datetime.now(datetime.timezone.utc).isoformat()
113
+ self.redis.hset(self.running_list, f'{self.id}|{job.name}', json.dumps({'timestamp': now, 'args': job_args}))
114
+
115
+ def remove_running(self, job: NutsJob):
116
+
117
+ self.redis.hdel(self.running_list, f'{self.id}|{job.name}')
118
+
119
+ def move_to_completed(self, job: NutsJob):
120
+ self.redis.sadd(self.completed_queue, job.name)
121
+
122
+ def queue_completed_jobs(self):
123
+
124
+ completed_jobs = self.redis.smembers(self.completed_queue)
125
+
126
+ for job_name in completed_jobs:
127
+ self.redis.srem(self.completed_queue, job_name)
128
+ job = [j for j in self.jobs if j.name == job_name.decode()][0]
129
+
130
+ next_execution = self.scheduler.get_next_execution(job.schedule).timestamp()
131
+
132
+ self.redis.zadd(self.scheduled_queue, {job.name: next_execution})
133
+
134
+ def run(self):
135
+
136
+ is_leader = self.check_leader()
137
+ if is_leader:
138
+ # Move ready jobs to the pending queue
139
+ self.move_scheduled_to_pending()
140
+
141
+ try:
142
+ data = self.redis.spop(self.pending_queue, 1)
143
+ [job_name, job_args] = json.loads(data[0])
144
+
145
+ job = [j for j in self.jobs if j.name == job_name][0]
146
+
147
+ self.move_pending_to_running(job, job_args)
148
+
149
+ except Exception as ex:
150
+ self.logger.error(ex)
151
+
152
+ try:
153
+ job.run(**job_args, **self.kwargs)
154
+
155
+ self.remove_running(job)
156
+
157
+ if job.success:
158
+ msg = f'SUCCESS: {job.name}, {job.result}'
159
+
160
+ self.logger.info(msg)
161
+ else:
162
+ self.logger.error(f'Error running job {job.name}: {job.error}')
163
+ if job.schedule:
164
+ self.move_job_to_completed(job)
165
+
166
+ except Exception as ex:
167
+ msg = f'Unhandled Error in job {job.name}: {ex}'
168
+ self.logger.error(ex)
169
+
170
+ # Post Execution
171
+
172
+ if is_leader:
173
+ self.queue_completed_jobs()
174
+
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2025 Sam Huffman
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.2
2
+ Name: nuts-scheduler
3
+ Version: 0.0.2
4
+ Summary: A Redis backed job runner
5
+ Home-page: https://github.com/huffmsa/nuts
6
+ Author: Sam Huffman
7
+ Author-email: Sam Huffman <huffmsa@gmail.com>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/huffmsa/nuts
10
+ Project-URL: Issues, https://github.com/huffmsa/nuts/issues
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: python-dateutil==2.9.0.post0
18
+ Requires-Dist: redis==5.2.1
19
+ Dynamic: author
20
+ Dynamic: home-page
21
+
22
+ <p align="center">
23
+ <img src="https://raw.githubusercontent.com/huffmsa/nuts/refs/heads/master/nuts_logox200.jpeg">
24
+ </p>
25
+
26
+ # Not Unother Task Scheduler
27
+
28
+ It's another Redis backed task scheduler. Supports queueable and cronable jobs.
@@ -0,0 +1,9 @@
1
+ nuts/__init__.py,sha256=QcT-F4p9G3JkxsKe1KQMHiQ-DSdfVHI3zPCYnBfYfVs,76
2
+ nuts/cron.py,sha256=8F0iaqIc0GTJUDqkHfspS2mqj0R3XK7uy6A-Bs-jSe0,7959
3
+ nuts/job.py,sha256=_m-1d48mCW75rYGB6b6n3UUjA08Qor0zyCygeL3j66Y,345
4
+ nuts/worker.py,sha256=PTl9eP-genJ31uIjEWxgSpSYvy1YtpM403dS5ZE8AxY,5444
5
+ nuts_scheduler-0.0.2.dist-info/LICENSE,sha256=OiB6fvIVxQsD517DqrsG6m7Ed2ICtVB36Lg8GBqiRfE,1055
6
+ nuts_scheduler-0.0.2.dist-info/METADATA,sha256=ucV8eQxISIt0cvh2tfByFvI6BsCUnsRKww73D0t99Xc,904
7
+ nuts_scheduler-0.0.2.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
8
+ nuts_scheduler-0.0.2.dist-info/top_level.txt,sha256=Oq5WsUt76n-idREHtZ74RlQQJWN9e8OI5OtGsT3qDZU,5
9
+ nuts_scheduler-0.0.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.8.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ nuts