Skip to content

Tasks

Like Starlette and any other Starlette based frameworks, in Esmerald you can define background tasks to run after the returning response.

You can use the Task and Task with any ASGI framework as if it was native.

This can be useful for those operations that need to happen after the request without blocking the client (the client doesn't have to wait to complete) from receiving that same response.

Also you can simply run them as non-blocking operations without relying on any ASGI framework, simple Python background tasks.

backgrounder.Task

Task(func, *args, **kwargs)

Bases: Repr

Task as a single instance can be easily achieved.

Example

from backgrounder import Task

async def send_email_notification(message: str):
    '''
    Sends an email notification
    '''
    send_notification(message)

task = Task(send_email_notification, "message to someone")
PARAMETER DESCRIPTION
func

Any callable to be executed by in the background. This can be async def of normal blocking def.

Example

from backgrounder import Task

# For blocking callables
def send_notification(message: str) -> None:
    ...

task = Task(send_notification, "A notification")
await task()

# For async callables
async def send_notification(message: str) -> None:
    ...

task = Task(send_notification, "A notification")
await task()

TYPE: Callable[P, Any]

*args

Any arguments of the callable.

Example

from backgrounder import Task

# For blocking callables
def send_notification(message: str, email: str) -> None:
    ...

task = Task(send_notification, "A notification", "user@example.com")

# For async callables
async def send_notification(message: str, email: str) -> None:
    ...

task = Task(send_notification, "A notification", "user@example.com")

TYPE: Any DEFAULT: ()

**kwargs

Any kwyword arguments of the callable.

Example

from typing import Any

from backgrounder import Task

data = {"message": "A notification", "email": "user@example.com"}

# For blocking callables
def send_notification(**kwargs: Any) -> None:
    message = kwargs.pop("message", None)
    email = kwargs.pop("email", None)

task = Task(send_notification, **data)

# For async callables
async def send_notification(**kwargs: Any) -> None:
    message = kwargs.pop("message", None)
    email = kwargs.pop("email", None)

task = Task(send_notification, **data)

TYPE: Any DEFAULT: {}

Source code in backgrounder/tasks.py
 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
def __init__(
    self,
    func: Annotated[
        Callable[P, Any],
        Doc(
            """
            Any callable to be executed by in the background.
            This can be `async def` of normal blocking `def`.

            **Example**

            ```python
            from backgrounder import Task

            # For blocking callables
            def send_notification(message: str) -> None:
                ...

            task = Task(send_notification, "A notification")
            await task()

            # For async callables
            async def send_notification(message: str) -> None:
                ...

            task = Task(send_notification, "A notification")
            await task()
            ```
            """
        ),
    ],
    *args: Annotated[
        Any,
        Doc(
            """
            Any arguments of the callable.

            **Example**

            ```python
            from backgrounder import Task

            # For blocking callables
            def send_notification(message: str, email: str) -> None:
                ...

            task = Task(send_notification, "A notification", "user@example.com")

            # For async callables
            async def send_notification(message: str, email: str) -> None:
                ...

            task = Task(send_notification, "A notification", "user@example.com")
            ```
            """
        ),
    ],
    **kwargs: Annotated[
        Any,
        Doc(
            """
            Any kwyword arguments of the callable.

            **Example**

            ```python
            from typing import Any

            from backgrounder import Task

            data = {"message": "A notification", "email": "user@example.com"}

            # For blocking callables
            def send_notification(**kwargs: Any) -> None:
                message = kwargs.pop("message", None)
                email = kwargs.pop("email", None)

            task = Task(send_notification, **data)

            # For async callables
            async def send_notification(**kwargs: Any) -> None:
                message = kwargs.pop("message", None)
                email = kwargs.pop("email", None)

            task = Task(send_notification, **data)
            ```
            """
        ),
    ],
) -> None:
    self.func = enforce_async_callable(func)
    self.args = args
    self.kwargs = kwargs

func instance-attribute

func = enforce_async_callable(func)

args instance-attribute

args = args

kwargs instance-attribute

kwargs = kwargs

backgrounder.Tasks

Tasks(tasks=None, as_group=False)

Bases: Task

Alternatively, the Tasks can also be used to be passed in.

Example

from datetime import datetime

from backgrounder import Task, Tasks

async def send_email_notification(message: str):
    '''
    Sends an email notification
    '''
    send_notification(message)


def write_in_file():
    with open("log.txt", mode="w") as log:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        content = f"Notification sent @ {now}"
        log.write(content)

tasks = Tasks([
    Task(send_email_notification, message="Account created"),
    Task(write_in_file),
])

await tasks()

When as_group is set to True, it will run all the tasks concurrently (as a group)

Example

from datetime import datetime

from backgrounder import Task, Tasks

async def send_email_notification(message: str):
    '''
    Sends an email notification
    '''
    send_notification(message)


def write_in_file():
    with open("log.txt", mode="w") as log:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        content = f"Notification sent @ {now}"
        log.write(content)

tasks = Tasks([
    Task(send_email_notification, message="Account created"),
    Task(write_in_file),
], as_group=True)

await tasks()
PARAMETER DESCRIPTION
tasks

A list of tasks to run execute.

Example

from datetime import datetime

from backgrounder import Task, Tasks

async def send_email_notification(message: str):
    '''
    Sends an email notification
    '''
    send_notification(message)


def write_in_file():
    with open("log.txt", mode="w") as log:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        content = f"Notification sent @ {now}"
        log.write(content)

tasks = Tasks([
    Task(send_email_notification, message="Account created"),
    Task(write_in_file),
])

await tasks()

TYPE: Union[Sequence[Task], None] DEFAULT: None

as_group

Boolean flag indicating if the tasks should be run concurrently, in other words, as a group.

Example

from datetime import datetime

from backgrounder import Task, Tasks

async def send_email_notification(message: str):
    '''
    Sends an email notification
    '''
    send_notification(message)


def write_in_file():
    with open("log.txt", mode="w") as log:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        content = f"Notification sent @ {now}"
        log.write(content)

tasks = Tasks([
    Task(send_email_notification, message="Account created"),
    Task(write_in_file),
], as_group=True)

await tasks()

TYPE: bool DEFAULT: False

Source code in backgrounder/tasks.py
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
def __init__(
    self,
    tasks: Annotated[
        Union[Sequence[Task], None],
        Doc(
            """
            A `list` of [tasks](#tasks) to run execute.

            **Example**

            ```python
            from datetime import datetime

            from backgrounder import Task, Tasks

            async def send_email_notification(message: str):
                '''
                Sends an email notification
                '''
                send_notification(message)


            def write_in_file():
                with open("log.txt", mode="w") as log:
                    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    content = f"Notification sent @ {now}"
                    log.write(content)

            tasks = Tasks([
                Task(send_email_notification, message="Account created"),
                Task(write_in_file),
            ])

            await tasks()
            ```
            """
        ),
    ] = None,
    as_group: Annotated[
        bool,
        Doc(
            """
            Boolean flag indicating if the tasks should be run concurrently, in other
            words, as a group.

            **Example**

            ```python
            from datetime import datetime

            from backgrounder import Task, Tasks

            async def send_email_notification(message: str):
                '''
                Sends an email notification
                '''
                send_notification(message)


            def write_in_file():
                with open("log.txt", mode="w") as log:
                    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    content = f"Notification sent @ {now}"
                    log.write(content)

            tasks = Tasks([
                Task(send_email_notification, message="Account created"),
                Task(write_in_file),
            ], as_group=True)

            await tasks()
            ```
            """
        ),
    ] = False,
):
    self.tasks = list(tasks) if tasks else []
    self.as_group = as_group

add_task

add_task(func, *args, **kwargs)

Another way of adding tasks to the Tasks object.

Example

from datetime import datetime

from backgrounder import Task, Tasks

async def send_email_notification(message: str):
    '''
    Sends an email notification
    '''
    send_notification(message)


def write_in_file():
    with open("log.txt", mode="w") as log:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        content = f"Notification sent @ {now}"
        log.write(content)

tasks = Tasks()
tasks.add_task(send_email_notification, message="Account created")
tasks.add_task(write_in_file)

await tasks()

Or if you want to run them concurrently.

Example

from datetime import datetime

from backgrounder import Task, Tasks

async def send_email_notification(message: str):
    '''
    Sends an email notification
    '''
    send_notification(message)


def write_in_file():
    with open("log.txt", mode="w") as log:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        content = f"Notification sent @ {now}"
        log.write(content)

tasks = Tasks(as_group=True)
tasks.add_task(send_email_notification, message="Account created")
tasks.add_task(write_in_file)

await tasks()
PARAMETER DESCRIPTION
func

TYPE: Callable[P, Any]

*args

TYPE: args DEFAULT: ()

**kwargs

TYPE: kwargs DEFAULT: {}

Source code in backgrounder/tasks.py
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
def add_task(self, func: Callable[P, Any], *args: P.args, **kwargs: P.kwargs) -> None:
    """
    Another way of adding tasks to the `Tasks` object.

    **Example**

    ```python
    from datetime import datetime

    from backgrounder import Task, Tasks

    async def send_email_notification(message: str):
        '''
        Sends an email notification
        '''
        send_notification(message)


    def write_in_file():
        with open("log.txt", mode="w") as log:
            now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            content = f"Notification sent @ {now}"
            log.write(content)

    tasks = Tasks()
    tasks.add_task(send_email_notification, message="Account created")
    tasks.add_task(write_in_file)

    await tasks()
    ```

    Or if you want to run them concurrently.

    **Example**

    ```python
    from datetime import datetime

    from backgrounder import Task, Tasks

    async def send_email_notification(message: str):
        '''
        Sends an email notification
        '''
        send_notification(message)


    def write_in_file():
        with open("log.txt", mode="w") as log:
            now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            content = f"Notification sent @ {now}"
            log.write(content)

    tasks = Tasks(as_group=True)
    tasks.add_task(send_email_notification, message="Account created")
    tasks.add_task(write_in_file)

    await tasks()
    ```
    """
    task = Task(func, *args, **kwargs)
    self.tasks.append(task)