I have a Firebase function set to run every 20 minutes using setInterval, but it’s executing more frequently than expected. Below is the relevant part of my code:
try {
const response = await axios.get(
"https://ll.thespacedevs.com/2.0.0/event/upcoming/?limit=50&offset=0",
{ timeout: 90000 }
);
return response.data.results;
} catch (error) {
console.error("Error fetching space events:", error);
if (retryCount < 3) {
// Retry up to 3 times
const waitTime = 900000 * (retryCount + 1); // 15, 30, 45 minutes
console.log(`Retrying in ${waitTime / 60000} minutes...`);
await new Promise((resolve) => setTimeout(resolve, waitTime));
return fetchSpaceEvents(retryCount + 1);
} else {
throw new Error("Max retries reached");
}
}
};
// Database update logic
const updateDatabase = async () => {
console.log("UPDATED THE DATABASE AT", new Date());
try {
const spaceEvents = await fetchSpaceEvents();
if (spaceEvents) {
const client = await getClient();
for (const event of spaceEvents) {
const query = { id: event.id };
const update = { $set: event };
const options = { upsert: true };
event.interested = event.interested ?? 0;
event.comments = event.comments ?? [];
await client
.db()
.collection<SpaceEvent>("SpaceEvents")
.updateOne(query, update, options);
}
}
} catch (error) {
console.error("Error updating database with space events:", error);
}
};
setInterval(updateDatabase, 1200000); // 20 minutes
I am observing the database update logs more frequently than the 20-minute interval. For example, the logs indicate updates at times like 11:47:04, then 11:49:41, 11:49:53, and so on, which is much shorter than the intended interval.
I’m running this on Firebase, and I use firebase emulators:start –only functions for local testing. I’m unsure why the function is being triggered so frequently. Is this a known issue with Firebase functions or the emulator, or is there something in my code causing this behavior?
Any insights or advice on how to troubleshoot this would be greatly appreciated.
2
Answers
Okay using the scheduled functions I was able to get it to work.
Thank you
What you’re trying to do isn’t at all supported by Cloud Functions. setInterval is not guaranteed to do what you expect, given that you don’t control the lifetime and activity of a Cloud Functions server instance when it’s not actively handling the code of a trigger. Cloud Functions may scale up the number of active server instances to handle the current load on a function, or scale it down to zero when nothing is being invoked. Neither of these behaviors are compatible with setInterval, which would only work on a single machine running continually.
If you want periodic execution of some code on a Cloud Functions backend, you should use a scheduled function instead.