Skip to content

Commit d406f68

Browse files
committed
chore:ruff formating
1 parent 589863c commit d406f68

21 files changed

+233
-156
lines changed

scheduler/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,4 @@
99
]
1010

1111
from scheduler.settings_types import QueueConfiguration, SchedulerConfig
12-
from scheduler.decorators import job
12+
from scheduler.decorators import job

scheduler/admin/task_admin.py

Lines changed: 40 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@ def job_execution_of(job: JobModel, task: Task) -> bool:
2222
def get_job_executions_for_task(queue_name: str, scheduled_task: Task) -> List[JobModel]:
2323
queue = get_queue(queue_name)
2424
job_list: List[JobModel] = JobModel.get_many(queue.get_all_job_names(), connection=queue.connection)
25-
res = sorted(list(filter(lambda j: job_execution_of(j, scheduled_task), job_list)),
26-
key=lambda j: j.created_at,
27-
reverse=True)
25+
res = sorted(
26+
list(filter(lambda j: job_execution_of(j, scheduled_task), job_list)), key=lambda j: j.created_at, reverse=True
27+
)
2828
return res
2929

3030

@@ -50,7 +50,10 @@ class TaskAdmin(admin.ModelAdmin):
5050
"""TaskAdmin admin view for all task models."""
5151

5252
class Media:
53-
js = ("admin/js/jquery.init.js", "admin/js/select-fields.js",)
53+
js = (
54+
"admin/js/jquery.init.js",
55+
"admin/js/select-fields.js",
56+
)
5457

5558
save_on_top = True
5659
change_form_template = "admin/scheduler/change_form.html"
@@ -90,18 +93,41 @@ class Media:
9093
fieldsets = (
9194
(
9295
None,
93-
dict(fields=(
94-
"name", "callable",
95-
("enabled", "timeout", "result_ttl"),
96-
"task_type",
97-
)),
96+
dict(
97+
fields=(
98+
"name",
99+
"callable",
100+
("enabled", "timeout", "result_ttl"),
101+
"task_type",
102+
)
103+
),
104+
),
105+
(
106+
None,
107+
dict(fields=("scheduled_time",), classes=("tasktype-OnceTaskType",)),
108+
),
109+
(
110+
None,
111+
dict(fields=("cron_string",), classes=("tasktype-CronTaskType",)),
112+
),
113+
(
114+
None,
115+
dict(
116+
fields=(
117+
(
118+
"interval",
119+
"interval_unit",
120+
),
121+
"repeat",
122+
),
123+
classes=("tasktype-RepeatableTaskType",),
124+
),
98125
),
99-
(None, dict(fields=("scheduled_time",), classes=("tasktype-OnceTaskType",)),),
100-
(None, dict(fields=("cron_string",), classes=("tasktype-CronTaskType",)),),
101-
(None, dict(fields=(("interval", "interval_unit",), "repeat"), classes=("tasktype-RepeatableTaskType",)),),
102126
(_("Queue settings"), dict(fields=(("queue", "at_front"), "job_name"))),
103-
(_("Previous runs info"),
104-
dict(fields=(("successful_runs", "last_successful_run"), ("failed_runs", "last_failed_run"))),),
127+
(
128+
_("Previous runs info"),
129+
dict(fields=(("successful_runs", "last_successful_run"), ("failed_runs", "last_failed_run"))),
130+
),
105131
)
106132

107133
@admin.display(description="Schedule")

scheduler/decorators.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,18 @@
99

1010
class job:
1111
def __init__(
12-
self,
13-
queue: Union["Queue", str, None] = None, # noqa: F821
14-
connection: Optional[ConnectionType] = None,
15-
timeout: Optional[int] = None,
16-
result_ttl: Optional[int] = None,
17-
job_info_ttl: Optional[int] = None,
18-
at_front: bool = False,
19-
meta: Optional[Dict[Any, Any]] = None,
20-
description: Optional[str] = None,
21-
on_failure: Optional[Union["Callback", Callable[..., Any]]] = None,
22-
on_success: Optional[Union["Callback", Callable[..., Any]]] = None,
23-
on_stopped: Optional[Union["Callback", Callable[..., Any]]] = None,
12+
self,
13+
queue: Union["Queue", str, None] = None, # noqa: F821
14+
connection: Optional[ConnectionType] = None,
15+
timeout: Optional[int] = None,
16+
result_ttl: Optional[int] = None,
17+
job_info_ttl: Optional[int] = None,
18+
at_front: bool = False,
19+
meta: Optional[Dict[Any, Any]] = None,
20+
description: Optional[str] = None,
21+
on_failure: Optional[Union["Callback", Callable[..., Any]]] = None,
22+
on_success: Optional[Union["Callback", Callable[..., Any]]] = None,
23+
on_stopped: Optional[Union["Callback", Callable[..., Any]]] = None,
2424
):
2525
"""A decorator that adds a ``delay`` method to the decorated function, which in turn creates a RQ job when
2626
called. Accepts a required ``queue`` argument that can be either a ``Queue`` instance or a string
@@ -48,6 +48,7 @@ def __init__(
4848
:param on_stopped: Callable to run when stopped
4949
"""
5050
from scheduler.helpers.queues import get_queue
51+
5152
if queue is None:
5253
queue = "default"
5354
self.queue = get_queue(queue) if isinstance(queue, str) else queue

scheduler/helpers/callback.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def _import_attribute(name: str) -> Callable[..., Any]:
5555
except ImportError:
5656
attribute_bits.insert(0, module_name_bits.pop())
5757

58-
if module is None: # maybe it's a builtin
58+
if module is None: # maybe it's a builtin
5959
try:
6060
return __builtins__[name]
6161
except KeyError:

scheduler/helpers/queues/queue_logic.py

Lines changed: 49 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,6 @@ def clean_registries(self, timestamp: Optional[float] = None) -> None:
117117
logger.exception(f"Job {self.name}: error while executing failure callback")
118118
raise
119119

120-
121120
else:
122121
logger.warning(
123122
f"{self.__class__.__name__} cleanup: Moving job to {self.failed_job_registry.key} "
@@ -189,24 +188,24 @@ def get_all_jobs(self) -> List[JobModel]:
189188
return JobModel.get_many(job_names, connection=self.connection)
190189

191190
def create_and_enqueue_job(
192-
self,
193-
func: FunctionReferenceType,
194-
args: Union[Tuple, List, None] = None,
195-
kwargs: Optional[Dict] = None,
196-
timeout: Optional[int] = None,
197-
result_ttl: Optional[int] = None,
198-
job_info_ttl: Optional[int] = None,
199-
description: Optional[str] = None,
200-
name: Optional[str] = None,
201-
at_front: bool = False,
202-
meta: Optional[Dict] = None,
203-
on_success: Optional[Callback] = None,
204-
on_failure: Optional[Callback] = None,
205-
on_stopped: Optional[Callback] = None,
206-
task_type: Optional[str] = None,
207-
scheduled_task_id: Optional[int] = None,
208-
when: Optional[datetime] = None,
209-
pipeline: Optional[ConnectionType] = None,
191+
self,
192+
func: FunctionReferenceType,
193+
args: Union[Tuple, List, None] = None,
194+
kwargs: Optional[Dict] = None,
195+
timeout: Optional[int] = None,
196+
result_ttl: Optional[int] = None,
197+
job_info_ttl: Optional[int] = None,
198+
description: Optional[str] = None,
199+
name: Optional[str] = None,
200+
at_front: bool = False,
201+
meta: Optional[Dict] = None,
202+
on_success: Optional[Callback] = None,
203+
on_failure: Optional[Callback] = None,
204+
on_stopped: Optional[Callback] = None,
205+
task_type: Optional[str] = None,
206+
scheduled_task_id: Optional[int] = None,
207+
when: Optional[datetime] = None,
208+
pipeline: Optional[ConnectionType] = None,
210209
) -> JobModel:
211210
"""Creates a job to represent the delayed function call and enqueues it.
212211
:param when: When to schedule the job (None to enqueue immediately)
@@ -258,23 +257,37 @@ def create_and_enqueue_job(
258257
def job_handle_success(self, job: JobModel, result: Any, result_ttl: int, connection: ConnectionType):
259258
"""Saves and cleanup job after successful execution"""
260259
job.after_execution(
261-
result_ttl, JobStatus.FINISHED,
260+
result_ttl,
261+
JobStatus.FINISHED,
262262
prev_registry=self.active_job_registry,
263-
new_registry=self.finished_job_registry, connection=connection)
264-
Result.create(connection, job_name=job.name, worker_name=job.worker_name, _type=ResultType.SUCCESSFUL,
265-
return_value=result, ttl=result_ttl)
263+
new_registry=self.finished_job_registry,
264+
connection=connection,
265+
)
266+
Result.create(
267+
connection,
268+
job_name=job.name,
269+
worker_name=job.worker_name,
270+
_type=ResultType.SUCCESSFUL,
271+
return_value=result,
272+
ttl=result_ttl,
273+
)
266274

267275
def job_handle_failure(self, status: JobStatus, job: JobModel, exc_string: str, connection: ConnectionType):
268276
# Does not set job status since the job might be stopped
269277
job.after_execution(
270-
SCHEDULER_CONFIG.DEFAULT_FAILURE_TTL, status,
278+
SCHEDULER_CONFIG.DEFAULT_FAILURE_TTL,
279+
status,
271280
prev_registry=self.active_job_registry,
272281
new_registry=self.failed_job_registry,
273-
connection=connection)
282+
connection=connection,
283+
)
274284
Result.create(
275-
connection, job.name, job.worker_name,
276-
ResultType.FAILED, SCHEDULER_CONFIG.DEFAULT_FAILURE_TTL,
277-
exc_string=exc_string
285+
connection,
286+
job.name,
287+
job.worker_name,
288+
ResultType.FAILED,
289+
SCHEDULER_CONFIG.DEFAULT_FAILURE_TTL,
290+
exc_string=exc_string,
278291
)
279292

280293
def run_job(self, job: JobModel) -> JobModel:
@@ -299,7 +312,7 @@ def run_job(self, job: JobModel) -> JobModel:
299312
return job
300313

301314
def enqueue_job(
302-
self, job_model: JobModel, connection: Optional[ConnectionType] = None, at_front: bool = False
315+
self, job_model: JobModel, connection: Optional[ConnectionType] = None, at_front: bool = False
303316
) -> JobModel:
304317
"""Enqueues a job for delayed execution without checking dependencies.
305318
@@ -350,10 +363,10 @@ def run_sync(self, job: JobModel) -> JobModel:
350363

351364
@classmethod
352365
def dequeue_any(
353-
cls,
354-
queues: List[Self],
355-
timeout: Optional[int],
356-
connection: Optional[ConnectionType] = None,
366+
cls,
367+
queues: List[Self],
368+
timeout: Optional[int],
369+
connection: Optional[ConnectionType] = None,
357370
) -> Tuple[Optional[JobModel], Optional[Self]]:
358371
"""Class method returning a Job instance at the front of the given set of Queues, where the order of the queues
359372
is important.
@@ -439,8 +452,9 @@ def cancel_job(self, job_name: str) -> None:
439452
if new_status == JobStatus.CANCELED:
440453
self.canceled_job_registry.add(pipe, job_name, 0)
441454
else:
442-
self.finished_job_registry.add(pipe, job_name,
443-
current_timestamp() + SCHEDULER_CONFIG.DEFAULT_FAILURE_TTL)
455+
self.finished_job_registry.add(
456+
pipe, job_name, current_timestamp() + SCHEDULER_CONFIG.DEFAULT_FAILURE_TTL
457+
)
444458
pipe.execute()
445459
break
446460
except WatchError:

scheduler/models/task.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -189,9 +189,9 @@ def is_scheduled(self) -> bool:
189189
return False
190190
# check whether job_id is in scheduled/queued/active jobs
191191
res = (
192-
(self.job_name in self.rqueue.scheduled_job_registry.all())
193-
or (self.job_name in self.rqueue.queued_job_registry.all())
194-
or (self.job_name in self.rqueue.active_job_registry.all())
192+
(self.job_name in self.rqueue.scheduled_job_registry.all())
193+
or (self.job_name in self.rqueue.queued_job_registry.all())
194+
or (self.job_name in self.rqueue.active_job_registry.all())
195195
)
196196
# If the job_id is not scheduled/queued/started,
197197
# update the job_id to None. (The job_id belongs to a previous run which is completed)

scheduler/redis_models/job.py

Lines changed: 29 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -128,9 +128,14 @@ def prepare_for_execution(self, worker_name: str, registry: JobNamesRegistry, co
128128
registry.add(connection, self.name, self.last_heartbeat.timestamp())
129129
self.save(connection=connection)
130130

131-
def after_execution(self, result_ttl: int, status: JobStatus, connection: ConnectionType,
132-
prev_registry: Optional[JobNamesRegistry] = None,
133-
new_registry: Optional[JobNamesRegistry] = None) -> None:
131+
def after_execution(
132+
self,
133+
result_ttl: int,
134+
status: JobStatus,
135+
connection: ConnectionType,
136+
prev_registry: Optional[JobNamesRegistry] = None,
137+
new_registry: Optional[JobNamesRegistry] = None,
138+
) -> None:
134139
"""After the job is executed, update the status, heartbeat, and other metadata."""
135140
self.status = status
136141
self.ended_at = utils.utcnow()
@@ -167,26 +172,26 @@ def get_call_string(self):
167172

168173
@classmethod
169174
def create(
170-
cls,
171-
connection: ConnectionType,
172-
func: FunctionReferenceType,
173-
queue_name: str,
174-
args: Union[List[Any], Optional[Tuple]] = None,
175-
kwargs: Optional[Dict[str, Any]] = None,
176-
result_ttl: Optional[int] = None,
177-
job_info_ttl: Optional[int] = None,
178-
status: Optional[JobStatus] = None,
179-
description: Optional[str] = None,
180-
timeout: Optional[int] = None,
181-
name: Optional[str] = None,
182-
task_type: Optional[str] = None,
183-
scheduled_task_id: Optional[int] = None,
184-
meta: Optional[Dict[str, Any]] = None,
185-
*,
186-
on_success: Optional[Callback] = None,
187-
on_failure: Optional[Callback] = None,
188-
on_stopped: Optional[Callback] = None,
189-
at_front: Optional[bool] = None,
175+
cls,
176+
connection: ConnectionType,
177+
func: FunctionReferenceType,
178+
queue_name: str,
179+
args: Union[List[Any], Optional[Tuple]] = None,
180+
kwargs: Optional[Dict[str, Any]] = None,
181+
result_ttl: Optional[int] = None,
182+
job_info_ttl: Optional[int] = None,
183+
status: Optional[JobStatus] = None,
184+
description: Optional[str] = None,
185+
timeout: Optional[int] = None,
186+
name: Optional[str] = None,
187+
task_type: Optional[str] = None,
188+
scheduled_task_id: Optional[int] = None,
189+
meta: Optional[Dict[str, Any]] = None,
190+
*,
191+
on_success: Optional[Callback] = None,
192+
on_failure: Optional[Callback] = None,
193+
on_stopped: Optional[Callback] = None,
194+
at_front: Optional[bool] = None,
190195
) -> Self:
191196
"""Creates a new job-model for the given function, arguments, and keyword arguments.
192197
:returns: A job-model instance.
@@ -260,7 +265,7 @@ def create(
260265

261266

262267
def _get_call_string(
263-
func_name: Optional[str], args: Any, kwargs: Dict[Any, Any], max_length: Optional[int] = None
268+
func_name: Optional[str], args: Any, kwargs: Dict[Any, Any], max_length: Optional[int] = None
264269
) -> Optional[str]:
265270
"""
266271
Returns a string representation of the call, formatted as a regular

scheduler/redis_models/result.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -31,19 +31,23 @@ class Result(StreamModel):
3131

3232
@classmethod
3333
def create(
34-
cls,
35-
connection: ConnectionType,
36-
job_name: str,
37-
worker_name: str,
38-
_type: ResultType,
39-
ttl: int,
40-
return_value: Any = None,
41-
exc_string: Optional[str] = None,
34+
cls,
35+
connection: ConnectionType,
36+
job_name: str,
37+
worker_name: str,
38+
_type: ResultType,
39+
ttl: int,
40+
return_value: Any = None,
41+
exc_string: Optional[str] = None,
4242
) -> Self:
4343
result = cls(
4444
parent=job_name,
45-
ttl=ttl, type=_type, return_value=return_value, exc_string=exc_string,
46-
worker_name=worker_name, )
45+
ttl=ttl,
46+
type=_type,
47+
return_value=return_value,
48+
exc_string=exc_string,
49+
worker_name=worker_name,
50+
)
4751
result.save(connection)
4852
return result
4953

scheduler/tests/jobs.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,12 @@ def test_args_kwargs(*args, **kwargs):
1818
kwargs_list = [f"{k}={v}" for (k, v) in kwargs.items()]
1919
return func.format(", ".join(args_list + kwargs_list))
2020

21+
2122
def two_seconds_job():
2223
sleep(2)
2324
logging.info(f"Job {_counter}")
2425

26+
2527
def long_job():
2628
sleep(1000)
2729
logging.info(f"Job {_counter}")

0 commit comments

Comments
 (0)