Check if Cloud Task Queue is empty

1.6k views Asked by At

I'm working on a project with a Node.js backend. It has a Cloud Task queue component and it creates hundreds of tasks. I need to run something once all the tasks are completed. I've been pouring over the Cloud Task queue documentation and searching online. However, I haven't found any documentation on how exactly to do this. All I need to know is how to determine if the task queue is empty. If it's empty after adding tasks, then the tasks are considered to be all completed.

My Cloud Task queue client is initialized like so: const client = new CloudTasksClient()

Edit:

I wanted to note some documentation I found here that seems to indicate it might provide what I'm looking for, but I don't know how to implement it, I don't see any examples. https://cloud.google.com/tasks/docs/reference/rpc/google.cloud.tasks.v2#google.cloud.tasks.v2.ListTasksResponse

1

There are 1 answers

2
Donnald Cucharo On BEST ANSWER

Here's the official documentation on how to list the tasks in a queue. Take note that this sample uses Application Default Credentials for authentication so you need to be logged in on gcloud CLI.

Also another reference. This example is about listing queues but it is also applicable to list tasks by using client.listTasks().

I tested this code and it worked:

const {CloudTasksClient} = require('@google-cloud/tasks');
const client = new CloudTasksClient();

async function main () {
  const request = {
    parent: 'projects/PROJECT-ID/locations/REGION/queues/QUEUE-NAME', 
  };

  const [tasklist] = await client.listTasks(request);

  if (tasklist.length > 0) {
    console.log('Tasks:');
    tasklist.forEach(tasklist => {
      console.log(`  ${tasklist.name}`);
    });
  } else {
    console.log('No tasks found on queue!');
  }
}
main();