你如何每隔一段时间运行一个云函数?

时间:2021-02-19 06:48:23

标签: firebase scheduled-tasks google-cloud-pubsub

我一直在尝试按照以下方式做一些事情:

export const refreshJob = functions.pubsub
    .schedule("every 1 minutes")
    .onRun(() => helloWorld());

export const helloWorld = functions.https.......

我想每分钟运行一次 helloWorld 云函数,但似乎无法弄清楚。

谢谢。

1 个答案:

答案 0 :(得分:2)

您似乎将基于 HTTP 的 Cloud Functions 与预定的 Cloud Functions 混为一谈。它们彼此独立。根据 helloWorld() 的功能,前进的道路不同。

HTTPS 可调用函数

如果您现有的函数是 HTTPS Callable 函数,则如下所示:

export const refreshJob = functions.pubsub
    .schedule("every 1 minutes")
    .onRun(() => helloWorld());

export const helloWorld = functions.https.onCall((data, context) => {
  // do the task
  // make sure to return a Promise
});

您可以将其编辑为:

export const refreshJob = functions.pubsub
    .schedule("every 1 minutes")
    .onRun((context) => {
      // do the task
      // make sure to return a Promise
    });

如果您希望您的函数可调用并按计划运行,您可以改为使用:

function handleHelloWorldTask(data, context) {
  // do the task
  // make sure to return a Promise
}

export const refreshJob = functions.pubsub
    .schedule("every 1 minutes")
    .onRun((context) => handleHelloWorldTask({ scheduled: true }, context));

export const helloWorld = functions.https.onCall(handleHelloWorldTask);

HTTPS 请求处理程序

如果您现有的函数是 HTTPS 请求处理程序,您将使用:

const FIREBASE_PROJECT_ID = JSON.parse(process.env.FIREBASE_CONFIG).projectId;

export const refreshJob = functions.pubsub
    .schedule("every 1 minutes")
    .onRun(async (context) => {
      const response = await fetch(`https://us-central1-${FIREBASE_PROJECT_ID}.cloudfunctions.net/helloWorld`);
      if (response.ok) {
        console.log('Triggered helloWorld successfully');
      } else {
        throw new Error(`Unexpected status code ${response.status} from helloWorld: ${await response.text()}`);
      }
    });

export const helloWorld = functions.https.onRequest((req, res) => {
  // do the task
  // make sure to call res.end(), res.send() or res.json()
});