gustavopch
gustavopch

Reputation: 931

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

Upvotes: 4

Views: 954

Answers (2)

Carlos
Carlos

Reputation: 46

In latest releases a feature was added to delete the tasks. You can pass an id to the TaksOptions

const queue = getFunctions().taskQueue("yourQueue");
// Enqueue and pass id to TaksOptions
await queue.enqueue({ 
...data
}, 
{
  id: idYouWillBeUsingToDelete,
  ...taskOptions
});

Delete the task

const queue = getFunctions().taskQueue("yourQueue");
// Use de delete method
await queue.delete(idYouWillBeUsingToDelete)

Upvotes: 3

Dharmaraj
Dharmaraj

Reputation: 50850

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.

Upvotes: 3

Related Questions