I could create a singleton class that lives in the server and keeps the list of tasks in memory and the list of task ids in a data table.
Keeping the list of tasks in memory makes the job faster if you have a persistent server.
Keeping the list of task ids in a data table allows to rebuild the list of tasks when the persistent server doesn’t persist or doesn’t exist.
The problem is not anvil.server.list_background_tasks()
being too slow. The problem is that is_running()
or get_state()
are very slow, and using them on a very long list makes the whole thing unusable. I can’t make them faster, but I can make the list shorter by only focusing on the tasks listed and filtered from the data table, or, even better, by not using them at all.
Adding a state
column on the task data table and having each task updating its state in the data table instead of using anvil.server.task_state
, allows to quickly get a short list of task states and ids. Sometimes this alone is enough, sometimes the task must be retrieved to check is_running()
or get_termination_status()
.
For now (pending the creation of the singleton class mentioned above) my solution is similar to what @ianb describes:
- generate a
session_id
- start the background task and pass the
session_id
argument to it - add a row to a table containing both
session_id
andtask_id
In then the background task:
- use the
session_id
to get its row - update
state
in that row instead of using anvil.server.task_state - let the table know, either in the
state
column or another dedicated column, when the task has completed its job . This will fail when the task times out, is killed, etc., but will help in most cases
At this point any server function can quickly get the tasks it’s interested on and their state most of the times, and can get the task object for deeper investigation when in need.
I would still like an answer to the question: How long do background tasks stay in the list?