---
title: background_task (Python agent API)
source: https://docs.newrelic.com/docs/apm/agents/python-agent/python-agent-api/backgroundtask-python-agent-api
---

## Syntax

```py
newrelic.agent.background_task(application=None, name=None, group=None)
```

Used to instrument a background task or other non-web transaction of finite run time.

## Description

This Python decorator can be used to instrument background tasks or other [non-web transactions](https://docs.newrelic.com/docs/apm/transactions/intro-transactions/monitor-background-processes-other-non-web-transactions) of finite run time. This is typically used to instrument non-web activity like worker processes, job-based systems, and standalone scripts. Transactions marked as background tasks are displayed as non-web transactions in the APM UI and separated from web transactions.

> #### ⚠️ IMPORTANT
>
> If a function isn't already instrumented, you can use [`function_trace()`](https://docs.newrelic.com/docs/apm/agents/python-agent/python-agent-api/functiontrace-python-agent-api) to create a function trace for that function within a background task.  Or you can use the [config file](https://docs.newrelic.com/docs/apm/agents/python-agent/custom-instrumentation/python-custom-instrumentation-config-file/#listing_functions) to instrument uninstrumented functions.

If a function using the background task decorator is called within the context of a web transaction, then the web transaction is marked as a background task. The measurement of the time taken begins when the original web transaction starts.

If you cannot use the decorator, one of these call formats may be more useful:

-   **The context manager**: If the tasks to be monitored will only be determined at runtime (and not import time), you can use the `BackgroundTask` context manager to directly wrap the execution of a block of code. (This is the context manager used by `BackgroundTaskWrapper`.)
-   **The wrapper**: If you know in advance where the specific functions you want to track are, you can use the `background_task` decorator. But if you don't know all the functions that need to be traced (for example, if they're being looked up dynamically as part of a routing system), then you must use the `BackgroundTaskWrapper` to wrap the function at the time of registration or at the time of calling.
-   **The path-based wrapper**: The path-based wrapper form is `wrap_background_task`.

For more on the differences between and uses of these function forms, see [Variable call formats](https://docs.newrelic.com/docs/python-agent-api-different-call-forms).

## Parameters

### Decorator and context manager parameters [#main-params]

```py
newrelic.agent.background_task(application=None, name=None, group=None)
```

```py
newrelic.agent.BackgroundTask(application=None, name=None, group=None)
```

Parameters for these calls:

| Parameter                            | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `application` _Application instance_ | Required. The application under which the data will be reported. Default is `None`. If left without a value, the application specified in the agent [configuration](https://docs.newrelic.com/docs/agents/python-agent/installation-configuration/python-agent-configuration) (config file or environment variable) will be used. For more on generating an application object, see the [`application()`](https://docs.newrelic.com/docs/agents/python-agent/python-agent-api/application) method. The application, even if specified, can still be overridden if `newrelic.app_name` is defined in the WSGI application per request environ dictionary. |
| `name` _string_ or _function_        | Required. The name of the transaction. Could be a function that accepts a callable_name parameter. The default value is `None`. By default, the name will be the name of the function the decorator has been applied to but you can override this by supplying this name.                                                                                                                                                                                                                                                                                                                                                                                |
| `group` _string_ or _function_       | Optional. The `group` represents the naming structure for the `name` parameter. This is used in the UI to set the [transaction type](https://docs.newrelic.com/docs/apm/applications-menu/monitoring/transactions-page#tx_functions). If not supplied, the group defaults to `Function` in expectation that the name is of the form `module:class.function` or `module:function` and represents the name of the function being executed. If you are creating a custom group, we recommend you prefix it with `Python/`.  Could be a function that accepts the same parameters as the function being wrapped.                                             |

### Wrapper parameters: [#wrapper-params]

```py
newrelic.agent.BackgroundTaskWrapper(wrapped, application=None, name=None, group=None)
```

`BackgroundTaskWrapper` takes the same [parameters](#main-params) as the `background_task` decorator and this additional `wrapped` parameter:

| Parameter                            | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `wrapped` _method_                   | Required. The method to be traced.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `application` _Application instance_ | Required. The application under which the data will be reported. Default is `None`. If left without a value, the application specified in the agent [configuration](https://docs.newrelic.com/docs/agents/python-agent/installation-configuration/python-agent-configuration) (config file or environment variable) will be used. For more on generating an application object, see the [`application()`](https://docs.newrelic.com/docs/agents/python-agent/python-agent-api/application) method. The application, even if specified, can still be overridden if `newrelic.app_name` is defined in the WSGI application per request environ dictionary. |
| `name` _string_ or _function_        | Required. The name of the transaction. Could be a function that accepts a callable_name parameter. The default value is `None`. By default, the name will be the name of the function the decorator has been applied to but you can override this by supplying this name.                                                                                                                                                                                                                                                                                                                                                                                |
| `group` _string_ or _function_       | Optional. The `group` represents the naming structure for the `name` parameter. This is used in the UI to set the [transaction type](https://docs.newrelic.com/docs/apm/applications-menu/monitoring/transactions-page#tx_functions). If not supplied, the group defaults to `Function` in expectation that the name is of the form `module:class.function` or `module:function` and represents the name of the function being executed. If you are creating a custom group, we recommend you prefix it with `Python/`.  Could be a function that accepts the same parameters as the function being wrapped.                                             |

### Path-based parameters: [#path-based-params]

```py
newrelic.agent.wrap_background_task(module, object_path, application=None, name=None, group=None)
```

`wrap_background_task` takes the same [parameters](#main-params) as the `background_task` decorator plus these additional parameters:

| Parameter                     | Description                                                                          |
| ----------------------------- | ------------------------------------------------------------------------------------ |
| `module` _module_ or _string_ | Required. The module containing the non-web function/activity you are instrumenting. |
| `object_path` _string_        | Required. The path to the module.                                                    |

## Examples

### `background_task` decorator example [#bg_task_example]

Here's an example of using the `background_task` decorator:

```py
@newrelic.agent.background_task()
def task():
    ...
```

### `BackgroundTask` context manager example [#context-mgr-example]

An example of using `BackgroundTask`:

```py
application = newrelic.agent.application()
name = newrelic.agent.callable_name(task)

with BackgroundTask(application, name):
    task()
```

An example of using `BackgroundTask` with a dynamic name:

```py
application = newrelic.agent.application()
name = lambda callable_name: callable_name.split('.')[-1]
group = lambda *args, **kwargs: f"Function/{args[1]}" 

with BackgroundTask(application, name, group):
    task()
```

Here's another example with more parameters:

```py
application = newrelic.agent.register_application(timeout=10.0)

def execute_task(task_name):
    with newrelic.agent.BackgroundTask(application, name=task_name, group='Task'):
        ...
```

### `BackgroundTaskWrapper` example [#wrapper-example]

An example of using the `BackgroundTaskWrapper`:

```py
task = newrelic.agent.BackgroundTaskWrapper(get_next_task())
result = task(*args, **kwargs)
```

In this example, if this call was made in a web transaction being monitored by an agent, the call will reclassify the web transaction as a background task. If, however, the call was made in a background thread or coroutine, then it would start the recording of a fresh background task transaction that tracks what occurs until the call returns.

## Troubleshooting

If the background task's transaction is not showing up in the UI, this could be because the transaction that was created by the background task was never exited or the task ran too long. If a background task runs for over 20 minutes, it is dropped by the server because it was considered too old to keep. Background tasks should not run for over 20 minutes and if they do they should be broken up into multiple background tasks.
