如何创建具有一定时间差的http目标云任务列表



我有一个firebase cloud函数,用于在firebase firestore上写入名为onWriteFile的特定文件时触发。

函数onWriteFile创建一个http云任务,在未来的某个时间运行,如下所示:

const { CloudTasksClient } = require('@google-cloud/tasks')
exports.onWriteFile = async (event, context) => { 
const project = 'my-projet'
const location = 'us-central1'
const queue = 'on-write-file'
const tasksClient = new CloudTasksClient()
const queuePath = tasksClient.queuePath(project, location, queue)
const url = `https://${location}-${project}.cloudfunctions.net/some-function`
//here is the core of question
const timestamp = event.value.fields.timestamp.integerValue
const json = { id: context.params.id }
const task = {
httpRequest: {
httpMethod: 'POST',
url,
body: Buffer.from(JSON.stringify(json)).toString('base64'),
headers: {
'Content-Type': 'application/json',
},
},
scheduleTime: {
seconds: timestamp
}
}
await tasksClient.createTask({ parent: queuePath, task })
};

这对我来说很好。

但是,例如在相同的onWrieteFile函数中,如何创建相差10秒的任务量?

也许我确实详细描述了这个问题。但我用以下代码解决了问题:

const { CloudTasksClient } = require('@google-cloud/tasks')
exports.onWriteFile = async (event, context) => { 
const project = 'my-projet'
const location = 'us-central1'
const queue = 'on-write-file'
const tasksClient = new CloudTasksClient()
const queuePath = tasksClient.queuePath(project, location, queue)
const url = `https://${location}-${project}.cloudfunctions.net/some-function`
const timestamp = event.value.fields.timestamp.integerValue
const json = { id: context.params.id }
//given a array to iterable
const iterable = Array.from(Array(6).keys())
//for each iteration I go add ten seconds to timestamp
const TEN_SECONDS = 10
const promises = iterable.map(async (i) => {
const seconds = Number(timestamp) + Number(i * TEN_SECONDS)
const task = {
httpRequest: {
httpMethod: 'POST',
url,
body: Buffer.from(JSON.stringify(fixtureId)).toString('base64'),
headers: {
'Content-Type': 'application/json',
},
},
scheduleTime: {
seconds: seconds
}
}
return await tasksClient.createTask({ parent: queuePath, task })
})
//then, I will have 6 cloud tasks with 10 seconds of difference
await Promise.all(promises)
};

感谢Doug Stevenson在Medium 上的帖子

相关内容

  • 没有找到相关文章

最新更新