All Posts in cron

August 28, 2012 - Comments Off on Getting Node.js and Cron to play nice(ly)

Getting Node.js and Cron to play nice(ly)

So, you've written a bang up, killer node.js script that tweets your facepage, instasmacks your flickr and makes your coffee, but you need it to run every hour, or you won't get retweets of lomo-bird-toasty looking coffee mugs pictures from your friends... What to do!!!

Easy! add the node.js script you have written to a cron job that runs on the server when you want and you're done. Unless it doesn't work.

There are a couple of reasons why a node.js script won't run in a cron job. To start with, make sure your script runs properly when you are logged in as a user with permission to run the script, for instance:

% node coffee.js

If that doesn't work, you'll need to figure out why before moving on. Make sure that node.js is installed; 'node -v' should return the installed version of node.js.

Next, you will need to make sure any calls to files use the absolute path. e.g.,

'... require('include.inc') ...' should read, '... require('/var/www/include.inc') ...'

The reason to do this is that when cron runs the script, it does so without a full shell environment to inform it about where it is, and what paths are relative to each other. This can be hard to debug, since you can still run your script on the command line even though it won't run in cron.

Now, onto the cron job, Crontab syntax can vary from system to system, be sure to check the docs for your setup.

Edit your crontab:

% crontab -e

for editing with vim or use nano,

% env EDITOR=nano crontab -e

Add the command line for your script, and include the full path for the node.js binary- since cron won't automatically know where it is located*.

*  */3  *  *  *      /usr/local/bin/node /var/www/coffee.js

Save the crontab file and wait for the magic to happen!

More with Cron:

Crontabs can be run on any schedule you desire. The example above tells it to run every 3 hours. The syntax can seem confusing at first, but then when you get to know it, it can still be confusing but at least you can make it do what you want. For example, you can set a job to run Monday - Friday, every hour between 8am and 5pm.

*  08-17  *  *  1-5     /usr/local/bin/node /var/www/coffee.js

 

*You can get the path to the node binary with:

% which node

Published by: chazcheadle in The Programming Mechanism
Tags: ,