簡體   English   中英

如何使用 pubsub 模擬器在本地調用 firebase 計划函數

[英]How to invoke firebase Schedule functions locally using pubsub emulator

我正在研究雲功能,尤其是計划功能。 我需要每 5 分鍾定期觸發 function,但僅在測試步驟中。 我需要在 pubsub 模擬器上運行它而不部署它。

怎么做?

我試過用firebase shell,但是只觸發了一次

 exports.scheduledFunctionPlainEnglish =functions.pubsub.schedule('every 2 minutes')
 .onRun((context) => {
    functions.logger.log("this runs every 2 minutes")
    return null;
}) 

計划函數加載到 Cloud Functions 模擬器運行時並綁定到 PubSub 模擬器主題。

但正如@samstern 所說( https://github.com/firebase/firebase-tools/issues/2034 ):

您必須使用 Pub/Sub 消息手動觸發它們。

你可以這樣做:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import { PubSub } from '@google-cloud/pubsub';

if (!admin.apps.length) {
  admin.initializeApp();
}

const pubsub = new PubSub({
  apiEndpoint: 'localhost:8085' // Change it to your PubSub emulator address and port
});

setInterval(() => {
  const SCHEDULED_FUNCTION_TOPIC = 'firebase-schedule-yourFunctionName';
  console.log(`Trigger sheduled function via PubSub topic: ${SCHEDULED_FUNCTION_TOPIC}`);
  const msg = await pubsub.topic(SCHEDULED_FUNCTION_TOPIC).publishJSON({
    foo: 'bar',
  }, { attr1: 'value1' });
}, 5 * 60 * 1000); // every 5 minutes

關於這個概念的附加信息(感謝@kthaas):

  1. https://github.com/firebase/firebase-tools/pull/2011/files#diff-6b2a373d8dc24c4074ee623d433662831cadc7c178373fb957c06bc12c44ba7b
  2. https://github.com/firebase/firebase-tools/pull/2011/files#diff-73f0f0ab73ffbf988f109e0a4c8b3b8a793f30ef33929928a892d605f0f0cc1f

正如您所說,您可以使用 firebase shell 來運行您的 function 一次。 而在firebase shell中,可以使用NodeJS命令。

使用 setInterval

firebase functions:shell ,使用setInterval每 2 分鍾運行一次 function。

user@laptop:~$ firebase functions:shell

✔  functions: functions emulator started at http://localhost:5000
i  functions: Loaded functions: myScheduledFunction
firebase > setInterval(() => myScheduledFunction(), 120000)

> this runs every 2 minutes

單行腳本

由於 firebase-tools 的 8.4.3 版本,尤其是這個 PR ,pipe 解決方案不再起作用。

在 Bash 中,您甚至可以在 pipe 中將setInterval命令設置為 firebase Z2591C98B1B1119FE62EB4289

user@laptop:~$ echo "setInterval(() => myScheduledFunction(), 120000)" | firebase functions:shell

對於那些在 2023 年看到這一點的人來說,它仍然不受支持。

我的解決方案是將執行“工作”的代碼從functions.pubsub.schedule中抽象出來並放入它們自己的函數中。 然后創建一個單獨的文件(我將其添加到函數文件夾的頂部),其中包含一個setInterval ,用於觸發上述抽象的 function。

例如,在您的代碼中的某處:

exports.myScheduledFunctionCode = () => {
  console.log('why, hello there interval');
}

/functions目錄頂部的timers.js (例如)文件中:

setInterval(() => {
  myScheduledFunctionCode();
}, 60000);

然后,您可以啟動 Firebase 模擬器套件。 在另一個終端 session 中,只需運行 vanilla $ node functions/timers.js 現在您預定的 function 代碼正在運行,您的整個模擬器套件也在運行。

希望這對某人有幫助!

計划功能目前不支持此功能。 文檔指出:

使用 shell,您可以模擬數據並執行 function 調用以模擬與 Emulator Suite 當前不支持的產品的交互:存儲、 PubSub 、分析、遠程配置、存儲、身份驗證和 Crashlytics。

計划函數是 pubsub 觸發器不受支持的擴展。

隨時向 Firebase 支持提出功能請求

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM