【发布时间】:2018-09-20 02:07:21
【问题描述】:
我想创建一个纯 Firebase 函数的 cron 作业。
下面是我的代码:
const functions = require('firebase-functions');
var admin = require('firebase-admin');
var serviceAccount = require('<private_key_path>');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://<project_name>.firebaseio.com'
});
cronJob_2min()
function cronJob_2min() {
console.log('cronjob started')
setTimeout(function () {
testTask1()
cronJob_2min()
}, 120000);
}
var testTask1Counter = 0
var testTask1Status = true
function testTask1() {
if (testTask1Status) {
testTask1Status = false //flag the task is started to avoid re-trigger again before the task is done
testTask1Counter++
console.log('testTask1 Executed: ', testTask1Counter)
testTask1Status = true //flag the task as completed to let next round trigger execute the function
}
}
在我部署它之后,它按预期工作,每 2 分钟它将执行一次 cronJob_2min() 并调用 testTask1() 函数。但它只运行了大约 20 分钟,因为日志只显示计数器直到 10。
似乎服务器会在一段时间后进入“睡眠模式”。
我知道在后台运行代码会消耗他的 CPU 配额,我可以接受。
但我想知道如何让它始终“清醒”?
谢谢。
编辑 1
旁注:我的云函数确实与其他 onCall 函数一起导出,但它太长了,所以我没有放这篇文章。我在上面发布的代码实际上是有效的,只是 cronJob_2min() 中的 console.log 被归类为我的 onCall 函数之一 sendEmail。
编辑 2
这样做甚至可以让它保持清醒吗?
//Setup the express, middleware, etc... I will skip that code here
router.get('/wakeUp', function (req, res) {
setTimeout(function () {
var theUrl = "https://us-central1-<project_name>.cloudfunctions.net/api/wakeUp"
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}, 120000);
return res.status(200).send('Tata! I am awake! (I suppose)')
})
app.use(router)
exports.api = functions.https.onRequest(app)
除非 Firebase Functions 足够聪明,可以避免来自它自己的 http 请求,否则它会工作吗?
【问题讨论】:
标签: javascript firebase google-cloud-functions cron-task