Cron jobs with node

Cron jobs not working!

Recently I discovered that my cron jobs weren’t working even though I could run the cron job command manually from the command line.

I made my cron entry by opening up my crontab file on my Ubuntu server.

1
root@Monkey:~# crontab -e

After reviewing how cron jobs work, I came up with this entry:

1
*/10 * * * * NODE_ENV=production node /var/www/email/current/cron/process-ready-jobs.js

This of course was the job that wasn’t working. There are two problems.

1. The script needs to be executable.

Here are the permissions for my script:

1
2
3
root@Monkey:/var/www/email/releases/20160407193434/cron# ls -l
total 4
-rw-rw-r-- 1 deployer deployers 720 Apr 7 15:34 process-ready-jobs.js

Notice that nobody has permission to execute the script. We need to add that in. So I added deployment task (in capistrano) to make the script executable.

1
chmod +x #{current_path}/cron/process-ready-jobs.js

Now my permissions are correct:

1
2
3
root@Monkey:/var/www/email/current/cron# ls -l
total 4
-rwxrwxr-x 1 deployer deployers 994 Jun 26 00:53 process-ready-jobs.js

2. The executable path for node needs to be explicit

When the cron job attempted to run the node command was unable to be found. We need to include the full path.

We can find the full path with the which command:

1
2
root@Monkey:~# which node
/usr/local/bin/node

With that knowledge we can update our script.

Here is my new cron entry:

1
*/10 * * * * NODE_ENV=production /usr/local/bin/node /var/www/email/current/cron/process-ready-jobs.js

More Info

Cron jobs are logged in the syslog

1
root@Monkey:~# tail /var/log/syslog

But I want some more info. By outputing data as my script runs, I can feed useful information to a log file.

Here’s my final cron entry with my log file in place:

1
*/10 * * * * NODE_ENV=production /usr/local/bin/node /var/www/email/current/cron/process-ready-jobs.js >> ~/cron-out.txt

Cron jobs are now working as expected!

avatar

Dev Blog