If you need to run a process that takes a long time, you want your app to carry on running while it executes.
Follow this quickstart to trigger an artificially slow-running HTTP request in the background, and return control to your main app while it executes.
Log in to Anvil and click ‘New Blank App’. Choose the Material Design theme.
In the App Browser, click the + next to Server Modules to add a new Server Module.
You will see a code editor with a yellow background.
Write this function into the Server Module
@anvil.server.background_task def make_slow_request(): response = anvil.http.request("https://httpstat.us/200?sleep=5000") # An API that provides slow responses print(response)
@anvil.server.background_task decorator means that this function can be run in the background.
Still in the server module, write a function that launches the Background Task
@anvil.server.callable def launch_slow_request_task(): task = anvil.server.launch_background_task('make_slow_request') return task
@anvil.server.callable decorator means this function can be called from the client code.
Go to the code for Form1. It looks like this:
At the end of the
__init__ method, write these lines:
self.task = anvil.server.call('launch_slow_request_task')
This means your function will run when the app starts, and the
task object will be stored. The
holds all available information about the task.
Now click the ‘Run’ button at the top of the screen.
The bottom of the Output Panel will show your Background Task running:
Click on Background Tasks in the Gear Menu :
You’ll see a table showing all the Background Tasks that this app has ever run:
Click on View Logs. You’ll be taken to the App Logs entry for that Task:
You can see the output from the Background Task. As expected, the Task printed the response from the test HTTP endpoint.
(It’s a Media object with a length of 0 bytes and no content - that’s because the test
https://httpstat.us) returns empty responses.)
Click on the button below to clone a finished version of this app into your account.
Want more depth on this subject?
You can pass data from a Background Task into the main app, access a task’s state, and terminate it programmatically.
You can also get a list of all the Background Tasks your app has.
Read more about Background Tasks to find out how.
Want another quickstart?
Every quickstart is on the Quickstarts page.