【问题标题】:Firebase synchronize background job that writes documents to FirestoreFirebase 同步将文档写入 Firestore 的后台作业
【发布时间】:2021-04-23 17:12:57
【问题描述】:

我有一个每分钟运行一次以更新文档的后台作业。 如果更新时间超过一分钟,我需要跳过下一个后台作业。 同步此逻辑的最佳方式是什么?

我现在有

export const pickWinnerBackgroundJob = functions.pubsub.schedule('every 1 minutes').onRun(async (context) => {
    const lock = await admin.firestore()
        .collection(`lock`)
        .doc(BG_JOB_LOCK_DOCUMENT_ID)
        .get();

    if (lock.exists && lock.data()?.locked == true) {
        return;
    }

    await admin.firestore()
        .collection(LOCK_COLLECTION_NAME)
        .doc(BG_JOB_LOCK_DOCUMENT_ID)
        .set({ locked: true })

    var promises: Promise<any>;
    // Add document update promises and execute job

    return Promise.all(promises).then(() => {
        return admin.firestore()
            .collection(LOCK_COLLECTION_NAME)
            .doc(BG_JOB_LOCK_DOCUMENT_ID)
            .set({ locked: false })
    });
});

这是一种有效的方法吗?

【问题讨论】:

    标签: node.js firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    这种方法看起来很合理,但您必须注意竞争条件。由于您可能无法完全阻止它们,因此您必须选择最适合您需求的策略,因此:当发生争用时,您可能会跳过一分钟太多,或者两个实例可能偶尔并行运行。

    或者,您可以 set the maximum number of instances 将此 Cloud Function 设置为 1,而不必担心代码中的问题。看起来 Firebase 包装器中的语法是:

    functions.pubsub.schedule('every 1 minutes').runWith({ maxInstances: 1 }).onRun(async (context) => {
    

    【讨论】:

    • 太棒了,maxInstances 正是我需要的,谢谢
    • 其实Property 'runWith' does not exist on type 'ScheduleBuilder'.ts(2339)
    • 是的,我想知道这一点。我没有看到该选项的任何例外或要求:github.com/firebase/firebase-functions/blob/…
    【解决方案2】:

    您还可以使用每个函数调用将下一个函数调用安排在当前函数调用之后一分钟。永远不能那样跑。 (您确实需要确保它们继续运行,因此您可能还需要一个看门狗)

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      相关资源
      最近更新 更多