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)
Background tasks cannot return Media objects directly - you have to store them in Data Tables and retrieve them from there.

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

Do you still have questions?

Our Community Forum is full of helpful information and Anvil experts.