Live Chat

We'll need to share your messages (and your email address if you're logged in) with our live chat provider, Drift. Here's their privacy policy.

If you don't want to do this, you can email us instead at contact@anvil.works.

Running tasks in the background

Background Tasks allow you to fire off a function to run in the background, leaving your main program to continue executing while the function is running.

In other words, the function is run asynchronously, it does not block the control flow.

Defining and Running

Any function decorated as @anvil.server.background_task can be run in the background.

To run a Background Task, call

anvil.server.launch_background_task('my_task_name', args...)

See Defining and Running for more information.

Communicating with Background Tasks

When a Background Task is launched, anvil.server.launch_background_task returns a Task object that can be used to send data from the Background Task to the main program. You can also get a Background Task’s status and stop it running using the Task object.

See Communicating Back for more information.

View Background Task status visually

You can view the status of all your Background Tasks by choosing “Background Tasks…” from the Gear Menu in the app builder.

A list of background tasks that have run, with their statuses and 'view logs' buttons.

List Background Tasks from code

To see all your Background Tasks, call anvil.server.list_background_tasks(), which will return a list of Task objects.

Running this function from the published version of your app will return only those Background Tasks that were started from the published version, and running from the development version (i.e. by clicking “Run” in the designer) will only return tasks started in that environment. To return all tasks regardless of environment, set the all_environments keyword argument to True:

anvil.server.list_background_tasks(all_environments=True)

Scheduled Tasks

You can trigger Background Tasks automatically according to a schedule. Users familiar with Cron will find this familiar.

Open the Scheduled Tasks dialog in the Gear Menu Gear Menu Icon to set up your Scheduled Tasks.

See Scheduled Tasks for more information.