每周定时执行,遍历 Firebase 数据库,删除过期的节点:
var config = require('./config.json');
var admin = require('firebase-admin');
var schedule = require('node-schedule');
var log4js = require('log4js');
log4js.configure({ // configure to use all types in different files.
appenders: [
{ type: 'file',
filename: config.firebase.log,
category: 'service',
maxLogSize: 20480000,
backups: 10
}
]
});
var logger = log4js.getLogger('service');
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.db
});
var defaultAppConfig = {
credential: admin.credential.cert(config.firebase.cert),
databaseURL: config.firebase.databaseURL
};
var defaultAppName = 'GoPeople-NodeJS-Admin';
var defaultApp = admin.initializeApp(defaultAppConfig, defaultAppName);
var isWorking = false;
var hasMoreData = true;
function init() {
logger.info('People Post remove signatures service start.');
// '0 0 0 * * 6' Saturday 00:00:00
// '*/5 * * * *' per 5 min
// '*/30 * * * * *' per 30 sec
var weekTask = schedule.scheduleJob('11 34 11 * * 2', function () {
logger.info('schedule week task start!');
var j = schedule.scheduleJob('*/30 * * * * *', function(){
startRemoveSignatures();
if(!hasMoreData){
logger.info('schedule task finished!');
logger.info();
logger.info();
schedule.cancelJob(j);
}
});
});
}
function startRemoveSignatures() {
var expiredDataCount = 0;
if(isWorking){
logger.info('startRemoveSignatures: hold on ...');
return;
}else{
isWorking = true;
logger.info();
logger.info('startRemoveSignatures: loading signatures data ...');
}
var signaturesRef = defaultApp.database().ref('signatures');
//signaturesRef.orderByChild("isChecked").equalTo(true).limitToLast(300).once("value")
signaturesRef.orderByChild("timestamp").limitToFirst(50).once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
var now = new Date();
var date = new Date(childData.date);
var dayDiff = parseInt((now - date) / (1000 * 60 * 60 * 24)); // day diff
if(dayDiff > 7){
expiredDataCount++;
signaturesRef.child(key).remove(function(error) {
console.log(key);
console.log(dayDiff);
console.log(error ? ("Uh oh! " + error) : "Success!");
logger.info(key);
if(error){
logger.error(error);
}else{
logger.info("Success! [ " + dayDiff + ' day ]');
}
});
}else{
console.log(key);
console.log(dayDiff);
logger.info(key);
logger.info("Jump!");
}
});
isWorking = false;
logger.info('expiredDataCount: ' + expiredDataCount);
if(expiredDataCount < 30){
hasMoreData = false;
}
});
}
init();