Google Cloud Functions Cron 作业不工作

Google Cloud Functions Cron Job Not Working

我正在尝试在 Firebase Cloud Functions 中设置 scheduled function。作为一个简单的测试,我尝试重新创建文档页面上显示的示例:

const functions = require('firebase-functions')

exports.scheduledFunction = functions.pubsub
  .schedule('every 5 minutes')
  .onRun(context => {
    console.log('This will be run every 5 minutes!')
    return null
  })

但是,当我 运行 firebase serve --only functions 时,出现以下错误:

function ignored because the pubsub emulator does not exist or is not running.

知道为什么我会收到此消息以及如何解决它吗?

来自 Firebase's local emulator 上的文档:

The Firebase CLI includes a Cloud Functions emulator which can emulate the following function types:

  • HTTPS functions
  • Callable functions
  • Cloud Firestore functions

因此本地 Firebase 模拟器目前不支持 pubsub,错误消息似乎证实了这一点。所以目前,您无法 运行 pubsub 在本地触发 Cloud Functions。

adding PubSub support to the emulator 的功能请求已提交。您可能想在那里阅读(并可能发表评论),因为所采取的方向可能符合您的需求,也可能不符合您的需求。

本地 shell 支持 invoking pubsub functions。这当然是完全不同的,但作为目前的解决方法可能很有用。

不管怎样,您需要在 firebase 中启用 pubsub 模拟器。将此添加到您的模拟器块:

{
  "emulators": {
    "pubsub": {
      "port": 8085
    },
  }
}

即便如此,它也只是创建了定义。模拟器不支持运行定时功能。

为了模拟该行为,我定义了一个 HTTP 触发器,我在其中手动向主题发送消息。对于计划主题,它是 firebase-schedule-。在您的情况下,它将是 firebase-schedule-scheduledFunction.

示例代码如下:

const pubsub = new PubSub()

export const triggerWork = functions.https.onRequest(async (request, response) => {
  await pubsub.topic('firebase-schedule-scheduledFunction').publishJSON({})
  response.send('Ok')
})

然后在命令行上,我定时触发HTTP功能

while [ 1 ];
  do wget -o /dev/null -O /dev/null http://localhost:5001/path/to/function/triggerWork;
  sleep 300;
done