Home > OS >  How to deploy the setInterval loop using cloud functions?
How to deploy the setInterval loop using cloud functions?

Time:09-26

I am doing the sample code enter image description here

To display the history event text repeatedly, I used the function setInterval (the following code).

// The code of the web app
// My code added 
const db = admin.firestore();

const express = require('express');
const app = express();
const axios = require('axios');
const cheerio = require('cheerio');
const https = require('https');

var status;

const url = 'https://online.mmvietnam.com/trung-tam/mm-an-phu/';

const interval = setInterval(function () {
var currentdate = new Date();
var hours = currentdate.getHours()   7 ;

if (hours >= 24) {
  hours = hours - 24 ;
}

var datetime =  hours   ":"
      currentdate.getMinutes()   ":"
      currentdate.getSeconds() ;

const agent = new https.Agent({
    rejectUnauthorized: false
});
axios.get(url, { httpsAgent: agent }).then(response => {
    var html = response.data;
    const $ = cheerio.load(html)
    var menu = $('.vertical-wrapper');
    var text = menu.find('.text-title').html();

    if (text !== null) {
       status = 'OPEN';                 
    }
    else {
       status = 'CLOSED';
    }
 });
async function quickstartAddData(db) {
  // [START firestore_setup_dataset_pt1]
  const docRef = db.collection('messages').doc('mmAnPhu');
  await docRef.set({
        name: 'Thu',
        text: datetime   ' '   'Mega market An Phu'   ' '   status,
        profilePicUrl: 'CamThu', 
        timestamp: datetime 
 });    
}
quickstartAddData(db);
}, 60000);

In the code above, the infor about profilePicUrl and timestamp, I do not the exactly infor, I only use them to consistent with the other code of the web app. I only need the text: datetime ' ' 'Mega market An Phu' ' ' status.

My problem is: the web app only display the history event text about 10 times, then it stop displaying. If I want to see the next history event text, I must to enter the input messages in Message (above figure) again.

How I make the function setInterval run continually to see the history event text displaying continually on Friendly Chat?

Thank you for all your helps!

CodePudding user response:

Cloud Functions are designed to run for relatively short periods of time after a certain event happens. They cannot be used to run continuous processes. Specifically: Cloud Functions can run no longer than 9 minutes.

So that explains exactly why your interval stops after about 10 times: it has reached the maximum time that a Cloud Function can be active.

Given that you're trying to run a piece of code every minute, you can schedule a Cloud Function to run every minute. That will not only solve the functional problem, but it will also be much cheaper - and you're not paying for the (typical majority of the) time in your current execution that the code it idle.

  • Related