Search code examples
node.jsfirebasegoogle-cloud-platformgoogle-cloud-functionsgoogle-cloud-tasks

How to cancel a task enqueued on Firebase Functions?


I'm talking about this: https://firebase.google.com/docs/functions/task-functions

I want to enqueue tasks with the scheduleTime parameter to run in the future, but I must be able to cancel those tasks.

I expected it would be possible to do something like this pseudo code:

const task = await queue.enqueue({ foo: true })

// Then...
await queue.cancel(task.id)

I'm using Node.js. In case it's not possible to cancel a scheduled task with firebase-admin, can I somehow work around it by using @google-cloud/tasks directly?

PS: I've also created a feature request: https://github.com/firebase/firebase-admin-node/issues/1753


Solution

  • The Firebase SDK doesn't return the task name/ID right now as in the code. If you need this functionality, I'd recommend filing a feature request and meanwhile use Cloud Tasks directly.

    You can simply create a HTTP Callable Function and then use the Cloud Tasks SDK to create a HTTP Target tasks that call this Cloud Function instead of using the onDispatch.

    // Instead of onDispatch()
    export const handleQueueEvent = functions.https.onRequest((req, res) => {
      // ...
    });
    

    Adding a Cloud Task:

    async function createHttpTask() {
      const parent = client.queuePath(project, location, queue);
    
      const task = {
        httpRequest: {
          httpMethod: 'POST', // change method if required
          url, // Use URL of handleQueueEvent function here
        },
      };
    
      const request = {
        parent: parent,
        task: task
      };
    
      const [response] = await client.createTask(request);
      return;
    }
    

    Checkout the documentation for more information.