node.js - 如何使用云函数部署 setInterval 循环?
问题描述
我正在做示例代码https://firebase.google.com/codelabs/firebase-cloud-functions#1。在此示例代码中,我想修改代码以在友好聊天中显示历史事件文本,而不是输入消息。我将代码添加到文件夹函数中的文件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);
在上面的代码中,关于profilePicUrl和timestamp的信息,我没有确切的信息,我只使用它们来与 web 应用程序的其他代码保持一致。我只需要文本: datetime + ' ' + 'Mega market An Phu' + ' ' + status。
我的问题是:网络应用程序仅显示历史事件文本大约 10 次,然后停止显示。如果我想查看下一个历史事件文本,我必须再次在Message(上图)中输入输入消息。
如何让函数setInterval持续运行以查看历史事件文本在友好聊天中持续显示?
感谢您的所有帮助!
解决方案
Cloud Functions 旨在在特定事件发生后运行相对较短的时间。它们不能用于运行连续流程。具体来说:Cloud Functions可以运行不超过 9 分钟。
这就解释了为什么您的间隔在大约 10 次后停止:它已达到云功能可以激活的最长时间。
鉴于您尝试每分钟运行一段代码,您可以安排云函数每分钟运行一次。这不仅可以解决功能问题,而且成本也会低得多 - 而且您无需为当前执行中代码空闲的(通常大部分)时间付费。