【问题标题】:How do you run a cloud function at an interval?您如何间隔运行云功能?
【发布时间】:2021-05-22 04:04:50
【问题描述】:

我一直在尝试做一些事情:

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

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

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

谢谢。

【问题讨论】:

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


    【解决方案1】:

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

    HTTPS 可调用函数

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

    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()
    });
    

    【讨论】:

    • 太棒了!谢谢!
    • @ChrisWingler 如果这回答了您的问题,请不要忘记将其标记为您接受的答案。
    猜你喜欢
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    相关资源
    最近更新 更多