[英]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):
正如您所說,您可以使用 firebase shell 來運行您的 function 一次。 而在firebase shell中,可以使用NodeJS命令。
在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 觸發器不受支持的擴展。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.