Search code examples
google-cloud-platformgoogle-cloud-functionsgoogle-cloud-tasks

Cloud task doesn't run on time


What I am trying to do is to change the data in firestore using cloud function and cloud task on a scheduled time. But cloud task doesn't run on time. It is executed right after adding task.

My code is like this.

index.js

exports.addTasks = functions.https.onCall((data, context) => {
  const client = new tasks.CloudTasksClient()

  const projectId = ...
  const queue = ...
  const location = ...

  const parent = client.queuePath(projectId, location, queue)

  const url = ... .cloudfunctions.net/doSomething?docId=' + docId

  const task = {
    httpRequest: {
      httpMethod: 'POST',
      url: url,
      scheduleTime: {
        seconds: 3 * 60 + Date.now() / 1000,
      }, 
    }
  }

  const request = {
    parent: parent,
    task: task,
  }

  client.createTask(request)
})

exports.doSomething = functions.https.onRequest((req, res) => {
  var db = admin.firestore()
  var docId = req.query.docId
  var docRef = db.collection('people').doc(docId)

  docRef.update({
    changeHere: true,
  })
})

I want to run doSomething function 3 minutes after addTasks is executed. What am I wrong with this?


Solution

  • scheduleTime is a property of the task object and not a property of httpRequest.

      const task = {
        httpRequest: {
          httpMethod: 'POST',
          url: url,
        },
        scheduleTime: {
          seconds: 3 * 60 + Date.now() / 1000,
        }, 
      }
    

    Here is the reference doc and sample code showing this.