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.

Defining and Running Background Tasks

Defining a Background Task

Decorate a function as @anvil.server.background_task

# Defining a Background Task
# In a Server Module:

@anvil.server.background_task
def train_my_network(training_iterations):
  """A long-running neural network training process."""
  for i in range(training_iterations):
    do_one_training_iteration()
    # Report progress percent
    anvil.server.task_state['progress'] = int((i+1 / float(training_iterations)) * 100)

Running a Background Task

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

  • First argument: name of function to execute
  • Other arguments: arguments to pass to the function
  • return value: a Task object for this task (see below).
Background Tasks can only be launched from Server Modules and Uplink scripts.
# Running a Background Task.
# In a Server Module:

@anvil.server.callable
def launch_training_task():
  """Fire off the training task, returning the Task object to the client."""
  task = anvil.server.launch_background_task('train_my_network', 200)
  return task