Server Functions in Server Modules or Jupyter Notebook

Just a general question, when would you write @anvil.server.callable or @anvil.server.background_task in the Server Modules of Anvil vs in your Jupyter Notebook? Are there differences in runtime for choosing one versus the other?

1 Like

When: Only when you have written a Python function that you intend to call from Anvil-related code.

Where: Only immediately before the definition of the function.

How to choose which decorator to use: If your function will always return within a few seconds, use callable. If there’s a possibility that the call will time out (last longer than 30 seconds before returning), use background_task.

You can have as many of each in the same Python program (e.g., notebook). In that case, they will all be using the same Python runtime (library), including the same interpreter, same CPU, and same region of memory. Speed will depend on what else the computer is doing.

To meet the callable's tighter time constraints, I would normally expect a callable to run at a higher priority than a background_task, but I’m not sure that Python (or Anvil) makes that distinction. Both are implemented using Python threads, and any thread can interrupt any other.

You don’t have to have it all in one program, though, and that opens the door to spreading the load across multiple CPUs, one per running program instance.