Skip to content
Jul 22 / admin

Need cron to run faster than 1 minute? Create a daemon in 60 seconds with shell scripts

The Problem

I recently encountered a problem in which files had to be transferred from a remote server to a local filesystem almost instantaneously. Initially, I created a shell script that would copy the files from remote to local. Then like a good novice sysadmin, I created a cron job to run every minute that triggered the script. It worked well enough, however I soon received complaints that the process was not instantaneous enough. Now if you’re wondering what possibly needs to be faster than one minute, to be fair, my client was printing labels, so waiting around for one minute for a label when they had hundreds to print in a day was frustrating for them.

The Solution

First I was asking my colleagues if there was a way to make cron run faster than one minute. However, that just seemed problematic, for if it ran too frequently, there could be a race condition. Ultimately, I decided that making a shell script that ran in an infinite loop would work perfectly. Of course I would needs a way to ensure the script was always running, and for that I would use cron. If cron realized the script was not running, it could initiate it. This would work well both if the script happened to stop, and if the server was rebooted for any reason.

Here’s the basics.

filename: /home/jeff/bin/bash_daemon.sh

#!/bin/bash

while [ 1 -eq 1 ]; do
# do some stuff
sleep 5
done

The basic premise is the loop. I added a five second wait, just to be somewhat courteous to the system, but you can set that to whatever you desire. Where it says #do some stuff, is where you put your logic.

filename: /home/jeff/bin/bash_cron.sh

#!/bin/bash

OUTPUT=`ps -ef | grep ‘[b]ash_daemon\.sh’`
if [ “$OUTPUT” ]
then
echo running
else
/home/jeff/bin/bash_daemon.sh
fi

This snippet checks to to see whether or not the process is currently running, if it is not, it starts it back up again. Notice the regular expression in the `grep` command, that stops `ps` from finding `grep` in the process list, and returns only the running script.

And of course don’t forget to edit your crontab. `su` to the user you will be running the script as and edit your crontab via `crontab -e`:

* * * * * /home/jeff/bin/bash_cron.sh > /dev/null 2>&1

That entry will run the script that checks that monitors your other script every minute. At least if it fails, it will be rebooted in a minute, but it’s unlikely it will ever fail. This is really useful to ensure that the script starts at bootstrap, which you could also accomplish by adding the daemon script to your startup scripts directory.

And there you have it, an seemingly instantaneous bash daemon.

Leave a Comment