Skip to content

SyncTask

Sync Task.

SyncTask

Bases: Generic[P, R]

SyncTask - a class for replacing a function with a @app.task and @shared_task decorator.

Example

from qtasks import QueueTasks

app = QueueTasks()

@app.task("test")
def test():
    print("This is a test!")

test.add_task()
Source code in src/qtasks/registries/sync_task_decorator.py
 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
class SyncTask(Generic[P, R]):
    """
    `SyncTask` - a class for replacing a function with a `@app.task` and `@shared_task` decorator.

    ## Example

    ```python
    from qtasks import QueueTasks

    app = QueueTasks()

    @app.task("test")
    def test():
        print("This is a test!")

    test.add_task()
    ```
    """

    def __init__(
        self,
        task_name: Annotated[
            str | None,
            Doc("""
                    Task name.

                    Default: `func.__name__`.
                    """),
        ] = None,
        priority: Annotated[
            int | None,
            Doc("""
                    The task has priority by default.

                    Default: `config.task_default_priority`.
                    """),
        ] = None,
        echo: Annotated[
            bool,
            Doc("""
                    Add SyncTask as the first parameter.

                    Default: `False`.
                    """),
        ] = False,
        max_time: Annotated[
            float | None,
            Doc("""
                    The maximum time it takes to complete a task in seconds.

                    Default: `None`.
                """),
        ] = None,
        retry: Annotated[
            int | None,
            Doc("""
                    The number of attempts to retry the task.

                    Default: `None`.
                    """),
        ] = None,
        retry_on_exc: Annotated[
            list[type[Exception]] | None,
            Doc("""
                    Exceptions under which the task will be re-executed.

                    Default: `None`.
                    """),
        ] = None,
        decode: Annotated[
            Callable | None,
            Doc("""
                    Task result decoder.
                """),
        ] = None,
        tags: Annotated[
            list[str] | None,
            Doc("""
                    Task tags.

                    Default: `None`.
                """),
        ] = None,
        description: Annotated[
            str | None,
            Doc("""
                    Description of the task.

                    Default: `None`.
                """),
        ] = None,
        generate_handler: Annotated[
            Callable | None,
            Doc("""
                    Handler generator.

                    Default: `None`.
                    """),
        ] = None,
        executor: Annotated[
            type[BaseTaskExecutor] | None,
            Doc("""
                    Class `BaseTaskExecutor`.

                    Default: `SyncTaskExecutor`.
                    """),
        ] = None,
        middlewares_before: Annotated[
            list[type[TaskMiddleware]] | None,
            Doc("""
                    Middleware that will be executed before the task.

                    Default: `Empty array`.
                    """),
        ] = None,
        middlewares_after: Annotated[
            list[type[TaskMiddleware]] | None,
            Doc("""
                    Middleware that will be executed after the task.

                    Default: `Empty array`.
                    """),
        ] = None,
        extra: Annotated[
            dict[str, Any] | None,
            Doc("""
                    Additional options.

                    Default: `Empty dictionary`.
                    """),
        ] = None,
        app: Annotated[
            Optional[QueueTasks],
            Doc("""
                    `QueueTasks` instance.

                    Default: `qtasks._state.app_main`.
                    """),
        ] = None,
    ):
        """
        Initializing a synchronous task.

        Args:
            task_name (str, optional): Task name. Default: `None`.
            priority (int, optional): Task priority. Default: `None`.
            echo (bool, optional): Add SyncTask as the first parameter. Default: `False`.
            max_time (float, optional): The maximum time the task will take to complete in seconds. Default: `None`.
            retry (int, optional): Number of attempts to retry the task. Default: `None`.
            retry_on_exc (List[Type[Exception]], optional): Exceptions under which the task will be re-executed. Default: `None`.
            decode (Callable, optional): Decoder of the task result. Default: `None`.
            tags (List[str], optional): Task tags. Default: `None`.
            description (str, optional): Description of the task. Default: `None`.
            generate_handler (Callable, optional): Handler generator. Default: `None`.
            executor (Type["BaseTaskExecutor"], optional): Class `BaseTaskExecutor`. Default: `None`.
            middlewares_before (List[Type["TaskMiddleware"]], optional): Middleware that will be executed before the task. Default: `Empty array`.
            middlewares_after (List[Type["TaskMiddleware"]], optional): Middleware that will be executed after the task. Default: `Empty array`.
            extra (Dict[str, Any], optional): Additional parameters. Default: `Empty dictionary`.
            app (QueueTasks, optional): `QueueTasks` instance. Default: `None`.
        """
        self.task_name = task_name
        self.priority = priority

        self.echo = echo

        self.max_time = max_time

        self.retry = retry
        self.retry_on_exc = retry_on_exc

        self.decode = decode
        self.tags = tags
        self.description = description

        self.executor = executor
        self.middlewares_before = middlewares_before or []
        self.middlewares_after = middlewares_after or []

        self.extra = extra or {}

        self._app = app

        self.ctx = SyncContext(
            task_name=task_name,
            generate_handler=generate_handler,
            executor=executor,
            app=app,
        )

    def add_task(
        self,
        *args: Annotated[
            Any,
            Doc("""
                    args of the task.

                    Default: `()`.
                    """),
        ],
        priority: Annotated[
            int | None,
            Doc("""
                    The task has priority.

                    Default: Task priority value.
                    """),
        ] = None,
        timeout: Annotated[
            float | None,
            Doc("""
                    Task timeout.

                    If specified, the task is returned via `qtasks.results.AsyncTask`.
                    """),
        ] = None,
        task_name: Annotated[
            str | None,
            Doc("""
                    Task name.

                    Default: The value of the task name.
                    """),
        ] = None,
        **kwargs: Annotated[
            Any,
            Doc("""
                    kwargs tasks.

                    Default: `{}`.
                    """),
        ],
    ) -> Union[Task, None]:
        """
        Add a task.

        Args:
            priority (int, optional): Task priority. Default: Task priority value.
            args (tuple, optional): task args. Default: `()`.
            kwargs (dict, optional): kwargs of tasks. Default: `{}`.
            timeout (float, optional): Task timeout. If specified, the task is returned via `qtasks.results.SyncTask`.
            task_name (str, optional): Task name. Default: The value of the task name.

        Returns:
            Task|None: Result of the task or `None`.

        Raises:
            ValueError: Task name is not specified.
        """
        if not task_name and not self.task_name:
            raise ValueError("Task name is not specified.")

        if not self._app:
            self._update_app()

        if priority is None:
            priority = self.priority

        return self._app.add_task(  # type: ignore
            task_name or self.task_name,  # type: ignore
            *args,
            priority=priority,
            timeout=timeout,
            **kwargs,
        )

    def __call__(
            self,
            *args: Annotated[
                Any,
                Doc("""
                        args of the task.

                        Default: `()`.
                        """),
            ],
            priority: Annotated[
                int | None,
                Doc("""
                        Task priority.

                        Default: Task priority value.
                        """),
            ] = None,
            timeout: Annotated[
                float | None,
                Doc("""
                        Task timeout.

                        If specified, the task is returned via `qtasks.results.AsyncTask`.
                        """),
            ] = None,
            task_name: Annotated[
                str | None,
                Doc("""
                        Task name.

                        Default: The value of the task name.
                        """),
            ] = None,
            **kwargs: Annotated[
                Any,
                Doc("""
                        kwargs tasks.

                        Default: `{}`.
                        """),
            ]
    ) -> SyncTaskCls:
        """Create SyncTaskCls instance.

        Args:
            priority (int, optional): Task priority. Default: Task priority value.
            args (tuple, optional): task args. Default: `()`.
            kwargs (dict, optional): kwargs of tasks. Default: `{}`.
            timeout (float, optional): Task timeout. If specified, the task is returned via `qtasks.results.SyncTask`.
            task_name (str, optional): Task name. Default: The value of the task name.
        """
        task_cls = SyncTaskCls(
            task_name=task_name or self.task_name,
            priority=priority or self.priority,
            timeout=timeout,
            args=args,
            kwargs=kwargs
        )
        task_cls.bind(self)
        return task_cls

    def _update_app(self):
        if not self._app:
            import qtasks._state

            if qtasks._state.app_main is None:
                raise ImportError("Unable to get app!")
            self._app = qtasks._state.app_main
        return

__call__(*args, priority=None, timeout=None, task_name=None, **kwargs)

Create SyncTaskCls instance.

Parameters:

Name Type Description Default
priority int

Task priority. Default: Task priority value.

None
args tuple

task args. Default: ().

()
kwargs dict

kwargs of tasks. Default: {}.

{}
timeout float

Task timeout. If specified, the task is returned via qtasks.results.SyncTask.

None
task_name str

Task name. Default: The value of the task name.

None
Source code in src/qtasks/registries/sync_task_decorator.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
def __call__(
        self,
        *args: Annotated[
            Any,
            Doc("""
                    args of the task.

                    Default: `()`.
                    """),
        ],
        priority: Annotated[
            int | None,
            Doc("""
                    Task priority.

                    Default: Task priority value.
                    """),
        ] = None,
        timeout: Annotated[
            float | None,
            Doc("""
                    Task timeout.

                    If specified, the task is returned via `qtasks.results.AsyncTask`.
                    """),
        ] = None,
        task_name: Annotated[
            str | None,
            Doc("""
                    Task name.

                    Default: The value of the task name.
                    """),
        ] = None,
        **kwargs: Annotated[
            Any,
            Doc("""
                    kwargs tasks.

                    Default: `{}`.
                    """),
        ]
) -> SyncTaskCls:
    """Create SyncTaskCls instance.

    Args:
        priority (int, optional): Task priority. Default: Task priority value.
        args (tuple, optional): task args. Default: `()`.
        kwargs (dict, optional): kwargs of tasks. Default: `{}`.
        timeout (float, optional): Task timeout. If specified, the task is returned via `qtasks.results.SyncTask`.
        task_name (str, optional): Task name. Default: The value of the task name.
    """
    task_cls = SyncTaskCls(
        task_name=task_name or self.task_name,
        priority=priority or self.priority,
        timeout=timeout,
        args=args,
        kwargs=kwargs
    )
    task_cls.bind(self)
    return task_cls

__init__(task_name=None, priority=None, echo=False, max_time=None, retry=None, retry_on_exc=None, decode=None, tags=None, description=None, generate_handler=None, executor=None, middlewares_before=None, middlewares_after=None, extra=None, app=None)

Initializing a synchronous task.

Parameters:

Name Type Description Default
task_name str

Task name. Default: None.

None
priority int

Task priority. Default: None.

None
echo bool

Add SyncTask as the first parameter. Default: False.

False
max_time float

The maximum time the task will take to complete in seconds. Default: None.

None
retry int

Number of attempts to retry the task. Default: None.

None
retry_on_exc List[Type[Exception]]

Exceptions under which the task will be re-executed. Default: None.

None
decode Callable

Decoder of the task result. Default: None.

None
tags List[str]

Task tags. Default: None.

None
description str

Description of the task. Default: None.

None
generate_handler Callable

Handler generator. Default: None.

None
executor Type['BaseTaskExecutor']

Class BaseTaskExecutor. Default: None.

None
middlewares_before List[Type['TaskMiddleware']]

Middleware that will be executed before the task. Default: Empty array.

None
middlewares_after List[Type['TaskMiddleware']]

Middleware that will be executed after the task. Default: Empty array.

None
extra Dict[str, Any]

Additional parameters. Default: Empty dictionary.

None
app QueueTasks

QueueTasks instance. Default: None.

None
Source code in src/qtasks/registries/sync_task_decorator.py
 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def __init__(
    self,
    task_name: Annotated[
        str | None,
        Doc("""
                Task name.

                Default: `func.__name__`.
                """),
    ] = None,
    priority: Annotated[
        int | None,
        Doc("""
                The task has priority by default.

                Default: `config.task_default_priority`.
                """),
    ] = None,
    echo: Annotated[
        bool,
        Doc("""
                Add SyncTask as the first parameter.

                Default: `False`.
                """),
    ] = False,
    max_time: Annotated[
        float | None,
        Doc("""
                The maximum time it takes to complete a task in seconds.

                Default: `None`.
            """),
    ] = None,
    retry: Annotated[
        int | None,
        Doc("""
                The number of attempts to retry the task.

                Default: `None`.
                """),
    ] = None,
    retry_on_exc: Annotated[
        list[type[Exception]] | None,
        Doc("""
                Exceptions under which the task will be re-executed.

                Default: `None`.
                """),
    ] = None,
    decode: Annotated[
        Callable | None,
        Doc("""
                Task result decoder.
            """),
    ] = None,
    tags: Annotated[
        list[str] | None,
        Doc("""
                Task tags.

                Default: `None`.
            """),
    ] = None,
    description: Annotated[
        str | None,
        Doc("""
                Description of the task.

                Default: `None`.
            """),
    ] = None,
    generate_handler: Annotated[
        Callable | None,
        Doc("""
                Handler generator.

                Default: `None`.
                """),
    ] = None,
    executor: Annotated[
        type[BaseTaskExecutor] | None,
        Doc("""
                Class `BaseTaskExecutor`.

                Default: `SyncTaskExecutor`.
                """),
    ] = None,
    middlewares_before: Annotated[
        list[type[TaskMiddleware]] | None,
        Doc("""
                Middleware that will be executed before the task.

                Default: `Empty array`.
                """),
    ] = None,
    middlewares_after: Annotated[
        list[type[TaskMiddleware]] | None,
        Doc("""
                Middleware that will be executed after the task.

                Default: `Empty array`.
                """),
    ] = None,
    extra: Annotated[
        dict[str, Any] | None,
        Doc("""
                Additional options.

                Default: `Empty dictionary`.
                """),
    ] = None,
    app: Annotated[
        Optional[QueueTasks],
        Doc("""
                `QueueTasks` instance.

                Default: `qtasks._state.app_main`.
                """),
    ] = None,
):
    """
    Initializing a synchronous task.

    Args:
        task_name (str, optional): Task name. Default: `None`.
        priority (int, optional): Task priority. Default: `None`.
        echo (bool, optional): Add SyncTask as the first parameter. Default: `False`.
        max_time (float, optional): The maximum time the task will take to complete in seconds. Default: `None`.
        retry (int, optional): Number of attempts to retry the task. Default: `None`.
        retry_on_exc (List[Type[Exception]], optional): Exceptions under which the task will be re-executed. Default: `None`.
        decode (Callable, optional): Decoder of the task result. Default: `None`.
        tags (List[str], optional): Task tags. Default: `None`.
        description (str, optional): Description of the task. Default: `None`.
        generate_handler (Callable, optional): Handler generator. Default: `None`.
        executor (Type["BaseTaskExecutor"], optional): Class `BaseTaskExecutor`. Default: `None`.
        middlewares_before (List[Type["TaskMiddleware"]], optional): Middleware that will be executed before the task. Default: `Empty array`.
        middlewares_after (List[Type["TaskMiddleware"]], optional): Middleware that will be executed after the task. Default: `Empty array`.
        extra (Dict[str, Any], optional): Additional parameters. Default: `Empty dictionary`.
        app (QueueTasks, optional): `QueueTasks` instance. Default: `None`.
    """
    self.task_name = task_name
    self.priority = priority

    self.echo = echo

    self.max_time = max_time

    self.retry = retry
    self.retry_on_exc = retry_on_exc

    self.decode = decode
    self.tags = tags
    self.description = description

    self.executor = executor
    self.middlewares_before = middlewares_before or []
    self.middlewares_after = middlewares_after or []

    self.extra = extra or {}

    self._app = app

    self.ctx = SyncContext(
        task_name=task_name,
        generate_handler=generate_handler,
        executor=executor,
        app=app,
    )

add_task(*args, priority=None, timeout=None, task_name=None, **kwargs)

Add a task.

Parameters:

Name Type Description Default
priority int

Task priority. Default: Task priority value.

None
args tuple

task args. Default: ().

()
kwargs dict

kwargs of tasks. Default: {}.

{}
timeout float

Task timeout. If specified, the task is returned via qtasks.results.SyncTask.

None
task_name str

Task name. Default: The value of the task name.

None

Returns:

Type Description
Union[Task, None]

Task|None: Result of the task or None.

Raises:

Type Description
ValueError

Task name is not specified.

Source code in src/qtasks/registries/sync_task_decorator.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
def add_task(
    self,
    *args: Annotated[
        Any,
        Doc("""
                args of the task.

                Default: `()`.
                """),
    ],
    priority: Annotated[
        int | None,
        Doc("""
                The task has priority.

                Default: Task priority value.
                """),
    ] = None,
    timeout: Annotated[
        float | None,
        Doc("""
                Task timeout.

                If specified, the task is returned via `qtasks.results.AsyncTask`.
                """),
    ] = None,
    task_name: Annotated[
        str | None,
        Doc("""
                Task name.

                Default: The value of the task name.
                """),
    ] = None,
    **kwargs: Annotated[
        Any,
        Doc("""
                kwargs tasks.

                Default: `{}`.
                """),
    ],
) -> Union[Task, None]:
    """
    Add a task.

    Args:
        priority (int, optional): Task priority. Default: Task priority value.
        args (tuple, optional): task args. Default: `()`.
        kwargs (dict, optional): kwargs of tasks. Default: `{}`.
        timeout (float, optional): Task timeout. If specified, the task is returned via `qtasks.results.SyncTask`.
        task_name (str, optional): Task name. Default: The value of the task name.

    Returns:
        Task|None: Result of the task or `None`.

    Raises:
        ValueError: Task name is not specified.
    """
    if not task_name and not self.task_name:
        raise ValueError("Task name is not specified.")

    if not self._app:
        self._update_app()

    if priority is None:
        priority = self.priority

    return self._app.add_task(  # type: ignore
        task_name or self.task_name,  # type: ignore
        *args,
        priority=priority,
        timeout=timeout,
        **kwargs,
    )