Excessively Running Firebase Function Due to setInterval Usage

My Firebase function is set to run every 20 minutes using setInterval, but it seems to be executing more frequently than expected. Here is an excerpt from 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

The database update logs are showing more frequent updates than the specified 20-minute interval. For example, I see updates at times like 11:47:04, then 11:49:41, 11:49:53, and so on, which is shorter than intended.

I am using Firebase and running firebase emulators:start --only functions for local testing. I'm not sure why the function is triggering more often than expected. Is this a known issue with Firebase functions or the emulator, or is there a problem in my code causing this behavior?

If you have any insights or advice on troubleshooting this issue, please share them. Your help would be greatly appreciated.

Answer №1

Attempting to achieve this goal through Cloud Functions is not supported at all. The setInterval function may not behave as expected because you do not have control over the lifespan and activity of a Cloud Functions server instance when it is not actively processing a trigger. Cloud Functions can increase or decrease the number of active server instances based on the current workload, which does not align with how setInterval functions by running continuously on a single machine.

If you require periodic code execution on a Cloud Functions backend, it would be best to utilize a scheduled function instead.

Answer №2

After implementing the scheduled functions, I was able to successfully make it work.

// Firebase functions and admin modules import
import * as functions from "firebase-functions";
import admin from "firebase-admin";
import { updateDatabase } from "../routes/spaceDevsRouter";

// Initializing the Firebase Admin SDK
admin.initializeApp();

// Cloud Function scheduled to update the database every 20 minutes
export const scheduledSpaceEventUpdate = functions.pubsub
  .schedule("every 20 minutes")
  .onRun(async (context) => {
    console.log("Scheduled update of space events initiated");
    try {
      await updateDatabase();
      console.log("Scheduled update of space events completed successfully");
    } catch (error) {
      console.error("Error encountered during scheduled update of space events:", error);
    }
  });

Thanks a lot!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assistance needed for jQuery functions running too early

Within my click function, I am setting certain flags and then calling two functions. However, I want these two functions to execute sequentially in order after the flags have been set. jQuery("#element").click(function(e){ var op = jQuery("#box" ...

Guidelines for choosing input using jQuery

I am looking to retrieve the value of an input using jQuery. Specifically, I need to extract the value of a hidden input with name="picture" when the user clicks on the حذف این بخش button by triggering the function deleteDefaultSection( ...

jQuery Mobile persists in loading the initial page of a multi-page document after form submission

After searching extensively for an alternative to data-ajax="false" without success, I've found myself in a dilemma. In my Phonegap application, utilizing jQuery Mobile to submit a form requires running it through the standard submit function in jQuer ...

Unable to bind knockout dropdownlist data during an ajax request

Trying to connect a dropdownlist in knockout with MVC 4. Below is the code snippet: Action public JsonResult GetUserTypes() { using (QuestApplicationEntities db = new QuestApplicationEntities()) { var usertypes = (from ...

Facing the Challenge: Overcoming Concurrency Issues with Promises

In the function "myMethod" within my "gulpfile.js", I aim to generate multiple Promises based on the size of an array passed as a parameter. It is crucial for all promises to be fulfilled before proceeding with any further actions upon calling this functio ...

Tips for adding parameters in the app.use function within the MongoClient.connect method

I was thinking that it might be more efficient to include app.use inside MongoClient.connect, rather than continuously calling the mongoclient inside the router. How can I access db.collection.find inside app.use? const database = dbm.db('db')` i ...

A curated collection saved in LocalStorage using React JS

I have implemented a LocalStorage feature to create a favorite list, but it only adds one item each time the page is reloaded. The items are retrieved from a JSON file. For a demonstration of how my code functions, check out this link: const [ storageIte ...

Using jQuery's ajax function to send data with a variable name of data field

I am trying to figure out how to dynamically add a variable to the name of the data field I want to send information to through ajax. Below is an example of the code I'm working on: var qty = $('#qty_'+value).val(); $.ajax({ url: &apo ...

Troubleshooting problem in Java related to encoding with XMLHttpRequest

Currently, I am utilizing XMLHttpRequest for an ajax call to my server. Let's consider the call: http = new XMLHTTPRequest(); var url = "http://app:8080/search.action?value=ñ" http.open("GET",url,true); http.setRequestHeader("Content-type", "applica ...

How can I determine the length of the returned array after a successful jQuery Ajax

I am struggling with looping through the Array returned from PHP. However, when I use jQuery .length, it returns 'undefined'. 'undefined' PHP: $items = array(); $items["country"] = "North Korea", $items["fruits"] = array( ...

Creating a visual comparison by using knockout side by side

I'm currently working on a project that requires me to display multiple items side by side for comparison. The ideal layout would be similar to Amazon's, where each item is represented by a vertical column with all relevant information about tha ...

How can I utilize the parseFloat feature within my dedicated parseFloat function located in an angular factory?

What is the solution for accessing parseFloat within an angular factory function named parseFloat? angular .module('myApp') .factory('mathService', [MathService]); function MathService() { return { parseFloat: myGl ...

The imageReference.delete method in Firebase storage is causing my app to crash with the error "signal SIGABRT"

I am utilizing: iOS - Swift 4 Cocoapods 1.4.0 Firebase (5.4.0) FirebaseCore (5.0.5) FirebaseStorage (3.0.0) Whenever I run the code provided, my app crashes with a signal SIGABRT error at the AppDelegate class and displays libc++abi.dylib: terminating w ...

Monitor for the specific parameter in the incoming GET request

My application is using the POST method to submit jobs remotely. After submitting a job, I receive a unique job ID from the POST request that allows me to check the status of the job using a GET request. $http.get('http://localhost:8090/jobs/'+i ...

Alert: A notification when navigating away from your site

Is there a way to notify users when they click on an external link that they are leaving your site? <div class="row"> <div class="col-lg-12"> <div class="form-group"> *If you need information on other applicable forms, you ...

Guide to accessing the content within an h1 tag with JavaScript

I currently have a setup with 3 pages: 2 of them are WordPress pages while the other page is a custom page template featuring a form. The first two pages were created using the wp-job manager plugin. The first page includes a dropdown menu with a list of a ...

I possess a primary menu with several submenus, yet I am encountering difficulty accessing the submenus. My goal is to efficiently navigate and access the appropriate submenu within the main menu

I am facing an issue with my CSS where the sub menu is currently showing from the left side, but I would like it to slide up and down instead. .outer { width: 100%; text-align: center; background-color: Gray; padding-top: 20px; bord ...

What would be the JavaScript counterpart to python's .text function?

When using Element.text, you can retrieve the text content of an element. Recently, in a separate discussion on SO, there was a Python script discussed that scraped data from the followers modal of an Instagram account. The script is designed to capture t ...

Jquery on method triggers a single event only

I am encountering an issue with adding and removing a class from an element using the on() method to handle click events. The code works fine on the first click, but subsequent clicks do not trigger the event anymore. Here is the code snippet: $(&apo ...

Exploring innovative methods for integrating dialog boxes in Chrome extensions?

Currently working on a Google Chrome extension and inquiring about the various choices for incorporating dialog boxes. I am looking for a solution that includes distinct head and body elements. The plan is to design custom-styled forms with jQuery. Are t ...