0

我有一个 firebase 云功能,可以在 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 })
};

这对我来说很好。

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

4

1 回答 1

0

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

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 上发帖

于 2020-03-27T04:08:37.383 回答