简体   繁体   中英

node.js cron job in web app

I use express.js and 'cron' module for auto db updating, so I dont know where should I add my cron init code, so I added it to my 'bin/www' , but after server started it spams like every seconds(but I need every 2 minutes), but if I changed 2 on 5 , its never started. here is my cron update js:

var catalogUpdater = require('../utils/catalogUpdater');
var descriptionDownloader = require('../utils/descriptionDownloader');

var CronJob = require('cron').CronJob;

var job = new CronJob('* */2 * * * *', function(){ 
    console.log('started');

}, 
function(){console.log('stop')},
true);

module.exports = job;

here is my ' bin/www ' code:

var app = require('../app');
var debug = require('debug')('shopnagby:server');
var http = require('http');
var config = require('../config');

var job = require('../cron/updateCron'); // include job updateCron to server startup;

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(config.get("port"));
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
.....

Where should I put my updateCron script?

You have incorrect cron syntax. Correct syntax have only 5 fields:

                field          allowed values
                -----          --------------
                minute         0-59
                hour           0-23
                day of month   0-31
                month          0-12 (or names, see below)
                day of week    0-7 (0 or 7 is Sun, or use names)

To run in every two minutes:

var job = new CronJob('*/2 * * * *', function(){ 
  console.log('started');
}, 
function(){console.log('stop')},
true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM