Ext*_*ght 4 javascript firebase google-cloud-pubsub google-cloud-functions
我正在研究云功能,尤其是计划功能。我需要每 5 分钟定期触发一个功能,但仅在测试步骤中。我需要在 pubsub 模拟器上运行它而不部署它。
怎么做?
我尝试使用 firebase shell,但它只触发了一次
exports.scheduledFunctionPlainEnglish =functions.pubsub.schedule('every 2 minutes')
.onRun((context) => {
functions.logger.log("this runs every 2 minutes")
return null;
})
Run Code Online (Sandbox Code Playgroud)
正如您所说,您可以使用 firebase shell 运行您的函数一次。\n并且在 firebase shell 中,您可以使用 NodeJS 命令。
\n里面firebase functions:shell,使用setInterval每 2 分钟运行一次函数。
user@laptop:~$ firebase functions:shell\n\n\xe2\x9c\x94 functions: functions emulator started at http://localhost:5000\ni functions: Loaded functions: myScheduledFunction\nfirebase > setInterval(() => myScheduledFunction(), 120000)\n\n> this runs every 2 minutes\nRun Code Online (Sandbox Code Playgroud)\n\n\n自 firebase-tools 版本 8.4.3 起,尤其是此 PR,管道解决方案不再起作用。
\n
在 Bash 中,您甚至可以通过管道传递setInterval命令发送到 firebase shell
user@laptop:~$ echo "setInterval(() => myScheduledFunction(), 120000)" | firebase functions:shell\nRun Code Online (Sandbox Code Playgroud)\n
计划函数被加载到 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
Run Code Online (Sandbox Code Playgroud)
关于这个概念的其他信息(感谢@kthaas):
目前计划功能不支持此功能。文档指出:
使用 shell,您可以模拟数据并执行函数调用,以模拟与模拟器套件当前不支持的产品的交互:Storage、PubSub、Analytics、Remote Config、Storage、Auth 和 Crashlytics。
计划函数是 pubsub 触发器不受支持的扩展。
| 归档时间: |
|
| 查看次数: |
2421 次 |
| 最近记录: |