Skip to content

BaseWorker - Пишем свой Воркер

Base worker class.

BaseWorker

Bases: Generic[TAsyncFlag], ABC

BaseWorker - An abstract class that is the foundation for Workers.

Example

from qtasks import QueueTasks
from qtasks.workers.base import BaseWorker

class MyWorker(BaseWorker):
    def __init__(self, name: str = None, broker: BaseBroker = None):
        super().__init__(name=name, broker=broker)
        pass
Source code in src/qtasks/workers/base.py
 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
362
363
364
365
366
367
368
369
370
371
372
373
class BaseWorker(Generic[TAsyncFlag], ABC):
    """
    `BaseWorker` - An abstract class that is the foundation for Workers.

    ## Example

    ```python
    from qtasks import QueueTasks
    from qtasks.workers.base import BaseWorker

    class MyWorker(BaseWorker):
        def __init__(self, name: str = None, broker: BaseBroker = None):
            super().__init__(name=name, broker=broker)
            pass
    ```
    """

    def __init__(
        self,
        name: Annotated[
            str,
            Doc("""
                    Project name. This name can be used by Worker.

                    Default: `QueueTasks`.
                    """),
        ] = "QueueTasks",
        broker: Annotated[
            Optional[BaseBroker],
            Doc("""
                    Broker `qtasks.brokers.base.BaseBroker`.

                    Default: `None`.
                    """),
        ] = None,
        log: Annotated[
            Logger | None,
            Doc("""
                    Logger.

                    Default: `qtasks.logs.Logger`.
                    """),
        ] = None,
        config: Annotated[
            QueueConfig | None,
            Doc("""
                    Config.

                    Default: `qtasks.configs.config.QueueConfig`.
                    """),
        ] = None,
        events: Annotated[
            Optional[BaseEvents],
            Doc("""
                    Events.

                    Default: `None`.
                    """),
        ] = None,
    ):
        """
        Initializing the base worker.

        Args:
            name (str, optional): Project name. Default: None.
            broker (BaseBroker, optional): Broker. Default: None.
            log (Logger, optional): Logger. Default: None.
            config (QueueConfig, optional): Config. Default: None.
        """
        self.name = name
        self.broker = broker
        self.config = config or QueueConfig()

        self.log = (
            log.with_subname("Worker")
            if log
            else Logger(
                name=self.name or "QueueTasks",
                subname="Worker",
                default_level=self.config.logs_default_level_server,
                format=self.config.logs_format,
            )
        )

        self._tasks: dict[str, TaskExecSchema] = {}
        self.events: BaseEvents | None = events
        self.task_middlewares_before: list[type[TaskMiddleware]] = []
        self.task_middlewares_after: list[type[TaskMiddleware]] = []

        self.task_executor: type[BaseTaskExecutor] | None = None

        self.plugins: dict[str, list[BasePlugin]] = {}

        self.num_workers = 0

        self.init_plugins()

    @overload
    def add(
        self: BaseWorker[Literal[False]],
        name: Annotated[
            str,
            Doc("""
                    Task name.
                    """),
        ],
        uuid: Annotated[
            UUID,
            Doc("""
                    UUID of the task.
                    """),
        ],
        priority: Annotated[
            int,
            Doc("""
                    Task priority.
                    """),
        ],
        created_at: Annotated[
            float,
            Doc("""
                    Creating a task in timestamp format.
                    """),
        ],
        args: Annotated[
            tuple,
            Doc("""
                    Task arguments of type args.
                    """),
        ],
        kwargs: Annotated[
            dict,
            Doc("""
                    Task arguments of type kwargs.
                    """),
        ],
    ) -> None: ...

    @overload
    async def add(
        self: BaseWorker[Literal[True]],
        name: Annotated[
            str,
            Doc("""
                    Task name.
                    """),
        ],
        uuid: Annotated[
            UUID,
            Doc("""
                    UUID of the task.
                    """),
        ],
        priority: Annotated[
            int,
            Doc("""
                    Task priority.
                    """),
        ],
        created_at: Annotated[
            float,
            Doc("""
                    Creating a task in timestamp format.
                    """),
        ],
        args: Annotated[
            tuple,
            Doc("""
                    Task arguments of type args.
                    """),
        ],
        kwargs: Annotated[
            dict,
            Doc("""
                    Task arguments of type kwargs.
                    """),
        ],
    ) -> None: ...

    @abstractmethod
    def add(
        self,
        name: Annotated[
            str,
            Doc("""
                    Task name.
                    """),
        ],
        uuid: Annotated[
            UUID,
            Doc("""
                    UUID of the task.
                    """),
        ],
        priority: Annotated[
            int,
            Doc("""
                    Task priority.
                    """),
        ],
        created_at: Annotated[
            float,
            Doc("""
                    Creating a task in timestamp format.
                    """),
        ],
        args: Annotated[
            tuple,
            Doc("""
                    Task arguments of type args.
                    """),
        ],
        kwargs: Annotated[
            dict,
            Doc("""
                    Task arguments of type kwargs.
                    """),
        ],
    ) -> None | Awaitable[None]:
        """
        Adding a task to the queue.

        Args:
            name (str): Name of the task.
            uuid (UUID): UUID of the task.
            priority (int): Task priority.
            created_at (float): Create a task in timestamp format.
            args (tuple): Task arguments of type args.
            kwargs (dict): Task arguments of type kwargs.
        """
        pass

    @overload
    def start(
        self: BaseWorker[Literal[False]],
        num_workers: Annotated[
            int | None,
            Doc("""
                    Number of workers.

                    Default: `None`.
                    """),
        ] = None,
    ) -> None: ...

    @overload
    async def start(
        self: BaseWorker[Literal[True]],
        num_workers: Annotated[
            int | None,
            Doc("""
                    Number of workers.

                    Default: `None`.
                    """),
        ] = None,
    ) -> None: ...

    @abstractmethod
    def start(
        self,
        num_workers: Annotated[
            int | None,
            Doc("""
                    Number of workers.

                    Default: `None`.
                    """),
        ] = None,
    ) -> None | Awaitable[None]:
        """
        Runs multiple task handlers. This function is enabled by the main `QueueTasks` instance via `run_forever`.

        Args:
            num_workers (int, optional): Number of workers. Default: 4.
        """
        pass

    @overload
    def stop(self: BaseWorker[Literal[False]]) -> None: ...

    @overload
    async def stop(self: BaseWorker[Literal[True]]) -> None: ...

    @abstractmethod
    def stop(self) -> None | Awaitable[None]:
        """Stops workers. This function is invoked by the main `QueueTasks` instance after the `run_forever` function completes."""
        pass

    def update_config(
        self,
        config: Annotated[
            QueueConfig,
            Doc("""
                    Config.
                    """),
        ],
    ) -> None:
        """
        Updates the broker config.

        Args:
            config (QueueConfig): Config.
        """
        self.config = config
        return

    def add_plugin(
        self,
        plugin: Annotated[
            BasePlugin,
            Doc("""
                    Plugin.
                    """),
        ],
        trigger_names: Annotated[
            list[str] | None,
            Doc("""
                    The name of the triggers for the plugin.

                    Default: Default: will be added to `Globals`.
                    """),
        ] = None,
    ) -> None:
        """
        Add a plugin to the class.

        Args:
            plugin (BasePlugin): Plugin
            trigger_names (List[str], optional): The name of the triggers for the plugin. Default: will be added to `Globals`.
        """
        trigger_names = trigger_names or ["Globals"]

        for name in trigger_names:
            if name not in self.plugins:
                self.plugins.update({name: [plugin]})
            else:
                self.plugins[name].append(plugin)
        return

    def init_plugins(self):
        """Initializing plugins."""
        pass

__init__(name='QueueTasks', broker=None, log=None, config=None, events=None)

Initializing the base worker.

Parameters:

Name Type Description Default
name str

Project name. Default: None.

'QueueTasks'
broker BaseBroker

Broker. Default: None.

None
log Logger

Logger. Default: None.

None
config QueueConfig

Config. Default: None.

None
Source code in src/qtasks/workers/base.py
 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
def __init__(
    self,
    name: Annotated[
        str,
        Doc("""
                Project name. This name can be used by Worker.

                Default: `QueueTasks`.
                """),
    ] = "QueueTasks",
    broker: Annotated[
        Optional[BaseBroker],
        Doc("""
                Broker `qtasks.brokers.base.BaseBroker`.

                Default: `None`.
                """),
    ] = None,
    log: Annotated[
        Logger | None,
        Doc("""
                Logger.

                Default: `qtasks.logs.Logger`.
                """),
    ] = None,
    config: Annotated[
        QueueConfig | None,
        Doc("""
                Config.

                Default: `qtasks.configs.config.QueueConfig`.
                """),
    ] = None,
    events: Annotated[
        Optional[BaseEvents],
        Doc("""
                Events.

                Default: `None`.
                """),
    ] = None,
):
    """
    Initializing the base worker.

    Args:
        name (str, optional): Project name. Default: None.
        broker (BaseBroker, optional): Broker. Default: None.
        log (Logger, optional): Logger. Default: None.
        config (QueueConfig, optional): Config. Default: None.
    """
    self.name = name
    self.broker = broker
    self.config = config or QueueConfig()

    self.log = (
        log.with_subname("Worker")
        if log
        else Logger(
            name=self.name or "QueueTasks",
            subname="Worker",
            default_level=self.config.logs_default_level_server,
            format=self.config.logs_format,
        )
    )

    self._tasks: dict[str, TaskExecSchema] = {}
    self.events: BaseEvents | None = events
    self.task_middlewares_before: list[type[TaskMiddleware]] = []
    self.task_middlewares_after: list[type[TaskMiddleware]] = []

    self.task_executor: type[BaseTaskExecutor] | None = None

    self.plugins: dict[str, list[BasePlugin]] = {}

    self.num_workers = 0

    self.init_plugins()

add(name, uuid, priority, created_at, args, kwargs) abstractmethod

add(name: Annotated[str, Doc('\n                    Task name.\n                    ')], uuid: Annotated[UUID, Doc('\n                    UUID of the task.\n                    ')], priority: Annotated[int, Doc('\n                    Task priority.\n                    ')], created_at: Annotated[float, Doc('\n                    Creating a task in timestamp format.\n                    ')], args: Annotated[tuple, Doc('\n                    Task arguments of type args.\n                    ')], kwargs: Annotated[dict, Doc('\n                    Task arguments of type kwargs.\n                    ')]) -> None
add(name: Annotated[str, Doc('\n                    Task name.\n                    ')], uuid: Annotated[UUID, Doc('\n                    UUID of the task.\n                    ')], priority: Annotated[int, Doc('\n                    Task priority.\n                    ')], created_at: Annotated[float, Doc('\n                    Creating a task in timestamp format.\n                    ')], args: Annotated[tuple, Doc('\n                    Task arguments of type args.\n                    ')], kwargs: Annotated[dict, Doc('\n                    Task arguments of type kwargs.\n                    ')]) -> None

Adding a task to the queue.

Parameters:

Name Type Description Default
name str

Name of the task.

required
uuid UUID

UUID of the task.

required
priority int

Task priority.

required
created_at float

Create a task in timestamp format.

required
args tuple

Task arguments of type args.

required
kwargs dict

Task arguments of type kwargs.

required
Source code in src/qtasks/workers/base.py
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
@abstractmethod
def add(
    self,
    name: Annotated[
        str,
        Doc("""
                Task name.
                """),
    ],
    uuid: Annotated[
        UUID,
        Doc("""
                UUID of the task.
                """),
    ],
    priority: Annotated[
        int,
        Doc("""
                Task priority.
                """),
    ],
    created_at: Annotated[
        float,
        Doc("""
                Creating a task in timestamp format.
                """),
    ],
    args: Annotated[
        tuple,
        Doc("""
                Task arguments of type args.
                """),
    ],
    kwargs: Annotated[
        dict,
        Doc("""
                Task arguments of type kwargs.
                """),
    ],
) -> None | Awaitable[None]:
    """
    Adding a task to the queue.

    Args:
        name (str): Name of the task.
        uuid (UUID): UUID of the task.
        priority (int): Task priority.
        created_at (float): Create a task in timestamp format.
        args (tuple): Task arguments of type args.
        kwargs (dict): Task arguments of type kwargs.
    """
    pass

add_plugin(plugin, trigger_names=None)

Add a plugin to the class.

Parameters:

Name Type Description Default
plugin BasePlugin

Plugin

required
trigger_names List[str]

The name of the triggers for the plugin. Default: will be added to Globals.

None
Source code in src/qtasks/workers/base.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
def add_plugin(
    self,
    plugin: Annotated[
        BasePlugin,
        Doc("""
                Plugin.
                """),
    ],
    trigger_names: Annotated[
        list[str] | None,
        Doc("""
                The name of the triggers for the plugin.

                Default: Default: will be added to `Globals`.
                """),
    ] = None,
) -> None:
    """
    Add a plugin to the class.

    Args:
        plugin (BasePlugin): Plugin
        trigger_names (List[str], optional): The name of the triggers for the plugin. Default: will be added to `Globals`.
    """
    trigger_names = trigger_names or ["Globals"]

    for name in trigger_names:
        if name not in self.plugins:
            self.plugins.update({name: [plugin]})
        else:
            self.plugins[name].append(plugin)
    return

init_plugins()

Initializing plugins.

Source code in src/qtasks/workers/base.py
371
372
373
def init_plugins(self):
    """Initializing plugins."""
    pass

start(num_workers=None) abstractmethod

start(num_workers: Annotated[int | None, Doc('\n                    Number of workers.\n\n                    Default: `None`.\n                    ')] = None) -> None
start(num_workers: Annotated[int | None, Doc('\n                    Number of workers.\n\n                    Default: `None`.\n                    ')] = None) -> None

Runs multiple task handlers. This function is enabled by the main QueueTasks instance via run_forever.

Parameters:

Name Type Description Default
num_workers int

Number of workers. Default: 4.

None
Source code in src/qtasks/workers/base.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
@abstractmethod
def start(
    self,
    num_workers: Annotated[
        int | None,
        Doc("""
                Number of workers.

                Default: `None`.
                """),
    ] = None,
) -> None | Awaitable[None]:
    """
    Runs multiple task handlers. This function is enabled by the main `QueueTasks` instance via `run_forever`.

    Args:
        num_workers (int, optional): Number of workers. Default: 4.
    """
    pass

stop() abstractmethod

stop() -> None
stop() -> None

Stops workers. This function is invoked by the main QueueTasks instance after the run_forever function completes.

Source code in src/qtasks/workers/base.py
315
316
317
318
@abstractmethod
def stop(self) -> None | Awaitable[None]:
    """Stops workers. This function is invoked by the main `QueueTasks` instance after the `run_forever` function completes."""
    pass

update_config(config)

Updates the broker config.

Parameters:

Name Type Description Default
config QueueConfig

Config.

required
Source code in src/qtasks/workers/base.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def update_config(
    self,
    config: Annotated[
        QueueConfig,
        Doc("""
                Config.
                """),
    ],
) -> None:
    """
    Updates the broker config.

    Args:
        config (QueueConfig): Config.
    """
    self.config = config
    return