Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Node.js for Your Cron Tasks

DZone's Guide to

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?

· Integration Zone
Free Resource

Today’s data climate is fast-paced and it’s not slowing down. Here’s why your current integration solution is not enough. Brought to you in partnership with Liaison Technologies.

Somewhere 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! 




Is iPaaS solving the right problems? Not knowing the fundamental difference between iPaaS and iPaaS+ could cost you down the road. Brought to you in partnership with Liaison Technologies.

Topics:
node ,javascript

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}