Reputation: 3699
I have an wepapp that need to collect data from another webservice everyday at 0:00 AM, and store them into MongoDB. My webapp is based on expressJS, and I don't know how to add a scheduler into my code. It looks weird that listening for client requests and check if it is the time to collect data at the same time. I think maybe I can provide a data collecting function as '/api/collectdata', and write a shell to visit this url address every 0:00 AM? Is there any elegant solution to combine a server with a scheduler?
Upvotes: 2
Views: 2499
Reputation: 1241
Not an expert but you can use various npm modules such as cron-job, node-schedule etc. But the main drawback that you may face is that they stop working when the server is not running (for example in case yo wana update your modules etc).
var schedule = require('node-schedule');
var jobDate = moment().startOf('day');
schedule.scheduleJob(jobDate, function () {
//your function
});
Upvotes: 4
Reputation: 3154
node-schedule
can be of great help to you.
This is the package info.
Node Schedule is for time-based scheduling, not interval-based scheduling. While you can easily bend it to your will, if you only want to do something like "run this function every 5 minutes", you'll find setInterval much easier to use, and far more appropriate. But if you want to, say, "run this function at the :20 and :50 of every hour on the third Tuesday of every month," you'll find that Node Schedule suits your needs better. Additionally, Node Schedule has Windows support unlike true cron since the node runtime is now fully supported.
You can install it using
npm install node-schedule
checkout this - Node-shedule
Also node-cron can be useful in your case.
Upvotes: 4