如何使用云函数部署 setInterval 循环?

How to deploy the setInterval loop using cloud functions?

我正在做示例代码https://firebase.google.com/codelabs/firebase-cloud-functions#1。在此示例代码中,我想修改代码以在 Friendly Chat 上显示历史事件文本而不是输入消息。我将我的代码添加到文件夹 functions 中的文件 index.js 中。当我部署这些功能时,我想显示历史事件文本(18:59:44 Mega market An Phu CLOSED),然后我需要通过在 Message(见下图)。

为了重复显示历史事件文本,我使用了函数setInterval(如下代码)。

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

在上面的代码中,关于profilePicUrltimestamp的信息,我没有确切的信息,我只是用它们来保持一致与网络应用程序的其他代码。我只需要 text: datetime + ' ' + 'Mega market An Phu' + ' ' + status.

我的问题是:网络应用程序只显示历史事件文本大约10次,然后就停止显示了。如果我想看到下一个历史事件文本,我必须再次输入 Message(上图)中的输入消息。

我如何使函数 setInterval 运行 不断地看到在 Friendly Chat 上不断显示的历史事件文本?

感谢大家的帮助!

Cloud Functions 旨在 运行 在特定事件发生后的相对较短时间内。它们不能用于 运行 连续过程。具体来说:云函数 can run no longer than 9 minutes.

这就准确地解释了为什么您的间隔在大约 10 次后停止:它已达到 Cloud Functions 可以激活的最长时间。

鉴于您正尝试每分钟 运行 一段代码,您可以每分钟 schedule a Cloud Function 到 运行。这不仅会解决功能问题,而且还会更便宜 - 而且您不会为当前执行中代码闲置的(通常大部分)时间付费。