Get id of background task from inside the task

I’d like to allow a background task to do a little setup on its task state, and then store its id into a data table. Some other code running on the client in a timer uses that id then to fetch the task state and update the GUI, but expects the task state to have certain fields.

In the docs at Anvil Docs | Communicating with Background Tasks, it shows three ways to get the id of a background task. None of those three ways would seem to allow a background task to get its own id.

Does a way exist that I’m not seeing in the docs?

3 Likes

Unfortunately, there’s currently no way to access a task ID from within the task, but it is on our list!

3 Likes

I have all of my background tasks separated out and get called by other functions that are organized as ‘background task generators’, this way I can grab information about the task object before I return it to the client, or another function etc.

This way you could grab the id from the task object, store it in your data table, then return the task object to whatever called it to begin with (or send it nowhere, whatever).

Example server module:

blah blah background task decorated functions

functions that only create task objects with a call to the background tasks and return the task object

functions that do neither of the above things

5 Likes

The workaround I’m using now is to create an id, then start the task passing the already created id to the task.

At this point both the function that starts the task and the task itself know the task id, the one I assigned to it.

4 Likes

I’ve just hit this one too. My workaround is…

  • Add a row to a datatable which includes a task_id column and a media column
  • Start the task passing the row as an argument and assign the task object to a variable
  • Update the row within the task to store the resulting media object
  • Using the task object, update the row to add the task_id
3 Likes

I just noticed this in the autocompleter:
anvil.server.context.background_task_id

3 Likes