1

I have a timed Cloud Function which I am trying to test in the Firebase Emulator. To do this, I am using the solution described here (How to invoke firebase Schedule functions locally using pubsub emulator) which triggers the scheduled function using a Pub/Sub message.

This solution successfully triggers the function, but it seems to be repeating its calls more than expected. For example, when I run the below code, it should be calling the scheduled function every minute: however, it runs the code once after a minute, then twice after 2 minutes (so it has run 3 times total), then three times after 3 times (so it has run 6 times total), and continues to increase its calls from there, which suggests setInterval() is being called more than once (I have setInterval() in my Firebase index.js file). Is there anyway to fix this? Thank you very much.

const pubsub = new PubSub({
  apiEndpoint: 'localhost:8085'
});

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' });
}, 1 * 60 * 1000); // every 1 minute
Redneys
  • 285
  • 1
  • 6
  • 18

1 Answers1

0

I replicated your case but there's no problem on my end. Here's my complete source code:

index.js:

const admin = require("firebase-admin");
const functions = require("firebase-functions");
const { PubSub } = require("@google-cloud/pubsub");

const pubsub = new PubSub();
admin.initializeApp();

const date_ob = new Date();


exports.pubsubScheduled = functions.pubsub.schedule("every mon 07:00").onRun((context) => {
    console.log("========== PUBSUB FUNCTION ==========");
    console.log("Time", new Date());
    return true;
});

trigger.js:

const admin = require("firebase-admin");
const functions = require("firebase-functions");
const { PubSub } = require("@google-cloud/pubsub");

admin.initializeApp();

var date_ob = new Date();
  
const pubsub = new PubSub({
 apiEndpoint: 'localhost:8085' // Change it to your PubSub emulator address and port
 });

  
    setInterval(() => {
    const SCHEDULED_FUNCTION_TOPIC = 'firebase-schedule-pubsubScheduled';
    console.log(`Trigger sheduled function via PubSub topic: ${SCHEDULED_FUNCTION_TOPIC} at ${new Date()}`);
    const msg =  pubsub.topic(SCHEDULED_FUNCTION_TOPIC).publishJSON({
      foo: 'bar',
    }, { attr1: 'value1' });
  }, 1 * 60 * 1000); // every 1 minute

After running the emulator then trigger the code(trigger.js) there's no problem and all is working well, no multi-output appeared. You can edit your question and add more details how we can reproduce your issue.

JM Gelilio
  • 3,482
  • 1
  • 11
  • 23