You are currently viewing the new Beta Editor Docs.
Switch to the Classic Editor Docs
You are currently viewing the Classic Editor Docs.
Switch to the Beta Editor Docs

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:

def train_my_network(training_iterations):
  """A long-running neural network training process."""
  for i in range(training_iterations):
    # 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:

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