如何使用 pubsub 模拟器在本地调用 firebase Schedule 函数

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)

sez*_*443 9

正如您所说,您可以使用 firebase shell 运行您的函数一次。\n并且在 firebase shell 中,您可以使用 NodeJS 命令。

\n

使用设置间隔

\n

里面firebase functions:shell,使用setInterval每 2 分钟运行一次函数。

\n
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\n
Run Code Online (Sandbox Code Playgroud)\n

单行脚本

\n
\n

自 firebase-tools 版本 8.4.3 起,尤其是此 PR,管道解决方案不再起作用。

\n
\n

在 Bash 中,您甚至可以通过管道传递setInterval命令发送到 firebase shell

\n
user@laptop:~$ echo "setInterval(() => myScheduledFunction(), 120000)" | firebase functions:shell\n
Run Code Online (Sandbox Code Playgroud)\n

  • 自 firebase-tools 版本 8.4.3 起,尤其是 [此 PR](https://github.com/firebase/firebase-tools/pull/2350),此解决方案不再有效。 (3认同)

Via*_*lov 6

计划函数被加载到 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):

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

  • 这怎么在我之前没有任何选票?这非常有效!我使用从您的答案借用的代码创建了一个 js 文件(而不是 ts 文件,不必担心编译它),并手动触发任务,而不是像这样的间隔:`nodefunctions/src/myTriggerfile.js` (2认同)

Dou*_*son 1

目前计划功能不支持此功能。文档指出

使用 shell,您可以模拟数据并执行函数调用,以模拟与模拟器套件当前不支持的产品的交互:Storage、PubSub、Analytics、Remote Config、Storage、Auth 和 Crashlytics。

计划函数是 pubsub 触发器不受支持的扩展。

请随时向 Firebase 支持人员提出功能请求

  • 这是 GitHub 上的[开放问题](https://github.com/firebase/firebase-tools/issues/2034)。 (2认同)