How do you run a cloud function at an interval?

Viewed 357

I've been trying to do something along these lines:

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

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

I'd like to run the helloWorld cloud function every minute, but can't seem to figure it out.

Thank you.

1 Answers

You seem to be mixing up the HTTP-based Cloud Functions with scheduled Cloud Functions. They are independent from each other. Depending on the function of helloWorld(), the way forward differs.

HTTPS Callable Function

If your existing function is a HTTPS Callable function, that looks like:

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

you would edit it into:

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

If you want your function to be callable AND run on a schedule, you could instead use:

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 Request Handler

If your existing function is a HTTPS Request handler, you would use:

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