Home > other >  How can I schedule a one-off background task in Firebase?
How can I schedule a one-off background task in Firebase?

Time:06-02

I'm working on improving code in an application that uses Firestore. I would like to ensure that Firestore will cleanup some bits of a transaction after the transaction is completed. Instead of doing this, I may opt to run the transaction and cleanup in one transaction. However, I believe this may also introduce a race condition if other architectural changes are not made.

Anyways, in working on this problem, I realized I don't know of a way (besides making a task queue) to dispatch a one-off task in Firestore.

I think the toy example below will help explain what I want to do.

// push cleanup task to Firestore to execute in 3000ms
await dispatchTransactionCleanup({id : "xxx", inMs : 3000}); // !important

// run the actual transaction, which should not take more than 1000 ms
await runMyTransaction({id : "xxx"});

// also dispatch a cleanup here, to reduce latency over the other cleanup.
// but, importantly this cleanup isn't guaranteed to run, e.g.,
// the server crashes between request to run transaction 
// and this part of the program.
await runManualCleanup({id : "xxx"});

So, how would I dispatchTransactionCleanup to run a one-off task at some point in the future? Is this possible without my own task queue? Or, do I need to introduce additional structure?

CodePudding user response:

Firestore doesn't have any sense of "task" or "queue". It just responds to the API calls you make, at the time you make them.

If you want a queuing mechanism, you'll have to build that, perhaps with some other software products. You already linked to one solution that uses Cloud Functions on the backend.

You might want to reconsider simply doing all the work in a single transaction. It's not clear why you think that this would be problematic. Maybe you could post a second question to explain in more detail what you tried that wouldn't work the way you expect.

  • Related