Skip to content

Commit f68a3de

Browse files
committed
refactor code
1 parent 3986fb5 commit f68a3de

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+300
-280
lines changed

docs/changelog.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## v4.0.0b3 🌈
4+
5+
Refactor the code to make it more organized and easier to maintain. This includes:
6+
- All types are under `types`.
7+
-
8+
39
## v4.0.0b2 🌈
410

511
### 🐛 Bug Fixes

docs/configuration.md

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
All default settings for scheduler can be in one dictionary in `settings.py`:
66

77
```python
8+
import os
89
from typing import Dict
9-
10-
from scheduler.settings_types import SchedulerConfiguration, Broker, QueueConfiguration, UnixSignalDeathPenalty
10+
from scheduler.types import SchedulerConfiguration, Broker, QueueConfiguration
1111

1212

1313
SCHEDULER_CONFIG = SchedulerConfiguration(
@@ -25,7 +25,6 @@ SCHEDULER_CONFIG = SchedulerConfiguration(
2525
DEFAULT_MAINTENANCE_TASK_INTERVAL=10 * 60, # The interval to run maintenance tasks in seconds. 10 minutes.
2626
DEFAULT_JOB_MONITORING_INTERVAL=30, # The interval to monitor jobs in seconds.
2727
SCHEDULER_FALLBACK_PERIOD_SECS=120, # Period (secs) to wait before requiring to reacquire locks
28-
DEATH_PENALTY_CLASS=UnixSignalDeathPenalty,
2928
)
3029
SCHEDULER_QUEUES: Dict[str, QueueConfiguration] = {
3130
'default': QueueConfiguration(

docs/installation.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,9 @@
1919
Note that the usage of `QueueConfiguration` is optional, you can use a simple dictionary, but `QueueConfiguration`
2020
helps preventing configuration errors.
2121
```python
22+
import os
2223
from typing import Dict
23-
from scheduler.settings_types import QueueConfiguration
24+
from scheduler.types import QueueConfiguration
2425

2526
SCHEDULER_QUEUES: Dict[str, QueueConfiguration] = {
2627
'default': QueueConfiguration(
@@ -52,7 +53,7 @@
5253

5354
4. Optional: Configure default values for queuing jobs from code:
5455
```python
55-
from scheduler.settings_types import SchedulerConfiguration, Broker, UnixSignalDeathPenalty
56+
from scheduler.types import SchedulerConfiguration, Broker
5657

5758
SCHEDULER_CONFIG = SchedulerConfiguration(
5859
EXECUTIONS_IN_PAGE=20,
@@ -69,7 +70,6 @@
6970
DEFAULT_MAINTENANCE_TASK_INTERVAL=10 * 60, # The interval to run maintenance tasks in seconds. 10 minutes.
7071
DEFAULT_JOB_MONITORING_INTERVAL=30, # The interval to monitor jobs in seconds.
7172
SCHEDULER_FALLBACK_PERIOD_SECS=120, # Period (secs) to wait before requiring to reacquire locks
72-
DEATH_PENALTY_CLASS=UnixSignalDeathPenalty,
7373
)
7474
```
7575

scheduler/__init__.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,7 @@
33
__version__ = importlib.metadata.version("django-tasks-scheduler")
44

55
__all__ = [
6-
"QueueConfiguration",
7-
"SchedulerConfiguration",
86
"job",
97
]
108

11-
from scheduler.settings_types import QueueConfiguration, SchedulerConfiguration
129
from scheduler.decorators import job

scheduler/admin/ephemeral_models.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
from django.contrib import admin
22

33
from scheduler import views
4-
from scheduler.models.queue import Queue
5-
from scheduler.models.worker import Worker
4+
from scheduler.models.ephemeral_models import Queue, Worker
65

76

87
class ImmutableAdmin(admin.ModelAdmin):

scheduler/admin/task_admin.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,11 @@
66
from django.http import HttpRequest
77
from django.utils.translation import gettext_lazy as _
88

9-
from scheduler.broker_types import ConnectionErrorTypes
10-
from scheduler.helpers import tools
119
from scheduler.helpers.queues import get_queue
12-
from scheduler.models.args import TaskArg, TaskKwarg
13-
from scheduler.models.task import Task, TaskType
10+
from scheduler.models import TaskArg, TaskKwarg, Task, TaskType, get_next_cron_time
1411
from scheduler.redis_models import JobModel
1512
from scheduler.settings import SCHEDULER_CONFIG, logger
13+
from scheduler.types import ConnectionErrorTypes
1614

1715

1816
def job_execution_of(job: JobModel, task: Task) -> bool:
@@ -142,7 +140,7 @@ def task_schedule(self, o: Task) -> str:
142140

143141
@admin.display(description="Next run")
144142
def next_run(self, o: Task) -> str:
145-
return tools.get_next_cron_time(o.cron_string)
143+
return get_next_cron_time(o.cron_string)
146144

147145
def change_view(self, request: HttpRequest, object_id, form_url="", extra_context=None):
148146
extra = extra_context or {}

scheduler/decorators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from functools import wraps
22
from typing import Any, Callable, Dict, Optional, Union
33

4-
from scheduler.broker_types import ConnectionType
4+
from scheduler.types import ConnectionType
55
from scheduler.helpers.callback import Callback
66

77
JOB_METHODS_LIST = list()

scheduler/helpers/queues/getters.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from typing import List, Set
22

3-
from scheduler.broker_types import ConnectionErrorTypes, BrokerMetaData
3+
from scheduler.types import ConnectionErrorTypes, BrokerMetaData
44
from scheduler.redis_models.worker import WorkerModel
55
from scheduler.settings import (
66
SCHEDULER_CONFIG,

scheduler/helpers/queues/queue_logic.py

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88
from redis import WatchError
99

10-
from scheduler.broker_types import ConnectionType, FunctionReferenceType
1110
from scheduler.helpers.callback import Callback
1211
from scheduler.helpers.utils import utcnow, current_timestamp
1312
from scheduler.redis_models import (
@@ -22,6 +21,7 @@
2221
)
2322
from scheduler.redis_models import JobStatus, SchedulerLock, Result, ResultType, JobModel
2423
from scheduler.settings import logger, SCHEDULER_CONFIG
24+
from scheduler.types import ConnectionType, FunctionReferenceType
2525

2626

2727
class InvalidJobOperation(Exception):
@@ -100,6 +100,7 @@ def clean_registries(self, timestamp: Optional[float] = None) -> None:
100100
Removed jobs are added to the global failed job queue.
101101
"""
102102
before_score = timestamp or current_timestamp()
103+
self.queued_job_registry.compact()
103104
started_jobs: List[Tuple[str, float]] = self.active_job_registry.get_job_names_before(
104105
self.connection, before_score
105106
)
@@ -119,15 +120,12 @@ def clean_registries(self, timestamp: Optional[float] = None) -> None:
119120

120121
else:
121122
logger.warning(
122-
f"{self.__class__.__name__} cleanup: Moving job to {self.failed_job_registry.key} "
123-
f"(due to AbandonedJobError)"
123+
f"Queue cleanup: Moving job to {self.failed_job_registry.key} (due to AbandonedJobError)"
124124
)
125-
job.set_status(JobStatus.FAILED, connection=pipeline)
126125
exc_string = (
127126
f"Moved to {self.failed_job_registry.key}, due to AbandonedJobError, at {datetime.now()}"
128127
)
129-
job.save(connection=pipeline)
130-
job.expire(ttl=-1, connection=pipeline)
128+
job.status = JobStatus.FAILED
131129
score = current_timestamp() + SCHEDULER_CONFIG.DEFAULT_FAILURE_TTL
132130
Result.create(
133131
connection=pipeline,
@@ -138,8 +136,8 @@ def clean_registries(self, timestamp: Optional[float] = None) -> None:
138136
exc_string=exc_string,
139137
)
140138
self.failed_job_registry.add(pipeline, job.name, score)
141-
job.save(connection=pipeline)
142139
job.expire(connection=pipeline, ttl=SCHEDULER_CONFIG.DEFAULT_FAILURE_TTL)
140+
job.save(connection=pipeline)
143141

144142
for registry in self.REGISTRIES.values():
145143
getattr(self, registry).cleanup(connection=self.connection, timestamp=before_score)
@@ -188,24 +186,24 @@ def get_all_jobs(self) -> List[JobModel]:
188186
return JobModel.get_many(job_names, connection=self.connection)
189187

190188
def create_and_enqueue_job(
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,
189+
self,
190+
func: FunctionReferenceType,
191+
args: Union[Tuple, List, None] = None,
192+
kwargs: Optional[Dict] = None,
193+
timeout: Optional[int] = None,
194+
result_ttl: Optional[int] = None,
195+
job_info_ttl: Optional[int] = None,
196+
description: Optional[str] = None,
197+
name: Optional[str] = None,
198+
at_front: bool = False,
199+
meta: Optional[Dict] = None,
200+
on_success: Optional[Callback] = None,
201+
on_failure: Optional[Callback] = None,
202+
on_stopped: Optional[Callback] = None,
203+
task_type: Optional[str] = None,
204+
scheduled_task_id: Optional[int] = None,
205+
when: Optional[datetime] = None,
206+
pipeline: Optional[ConnectionType] = None,
209207
) -> JobModel:
210208
"""Creates a job to represent the delayed function call and enqueues it.
211209
:param when: When to schedule the job (None to enqueue immediately)
@@ -312,7 +310,7 @@ def run_job(self, job: JobModel) -> JobModel:
312310
return job
313311

314312
def enqueue_job(
315-
self, job_model: JobModel, connection: Optional[ConnectionType] = None, at_front: bool = False
313+
self, job_model: JobModel, connection: Optional[ConnectionType] = None, at_front: bool = False
316314
) -> JobModel:
317315
"""Enqueues a job for delayed execution without checking dependencies.
318316
@@ -363,10 +361,10 @@ def run_sync(self, job: JobModel) -> JobModel:
363361

364362
@classmethod
365363
def dequeue_any(
366-
cls,
367-
queues: List[Self],
368-
timeout: Optional[int],
369-
connection: Optional[ConnectionType] = None,
364+
cls,
365+
queues: List[Self],
366+
timeout: Optional[int],
367+
connection: Optional[ConnectionType] = None,
370368
) -> Tuple[Optional[JobModel], Optional[Self]]:
371369
"""Class method returning a Job instance at the front of the given set of Queues, where the order of the queues
372370
is important.
@@ -382,6 +380,8 @@ def dequeue_any(
382380

383381
while True:
384382
registries = [q.queued_job_registry for q in queues]
383+
for registry in registries:
384+
registry.compact()
385385

386386
registry_key, job_name = QueuedJobRegistry.pop(connection, registries, timeout)
387387
if job_name is None:

scheduler/helpers/tools.py

Lines changed: 0 additions & 77 deletions
This file was deleted.

0 commit comments

Comments
 (0)