Using Node.js for Your Cron Tasks
Using Node.js for Your Cron Tasks
Can't bring yourself to code in any language other than JavaScript, but need the reliability of cron tasks?
Join the DZone community and get the full member experience.
Join For FreeSomewhere along your journey with Node.js it will hit you - you need to run a task as a cron job. This quick tip will show you how to add this ability to your project using two Node packages.
Node Crontab
First, we'll add a package to enable you to define cron based tasks: node-crontab. To install it, just run
npm install node-crontab
Using it in your application is just as simple. Once you have required the module, you can just pass through your callback to the scheduleJob function as the second argument.
var crontab = require('node-crontab');
var jobId = crontab.scheduleJob("*/2 * * * *", function(){
//This will call this function every 2 minutes
console.log("It's been 2 minutes!");
});
The first parameter is the time at which the task should be run, in crontab format (you can see more about this format here)
So, that's given us a repeating task - that's all you'd want right? Well......
Introducing PM2
PM2 is a process manager for Node.js applications. Among it's other useful characteristics, the most useful part of it is that it brings your Node process back to life if it crashes for any reason. If you have a long running cron process going on a machine, this is a useful superpower to have.
First you'll want to install pm2 globally using
npm install pm2 -g
Now, instead of starting your app using the node binary, you'll start it using pm2
pm2 start app.js
You can check which processes are running using
pm2 list
When your app is out on production, you'll be happy you used PM2!
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}