3

let us suppose I have a cron job like this:

*/15 * * * * /path/to/thedaemon

The daemon (it being a python daemon via from daemon import runner) will not allow multiple instances of itself, which in itself is quite nice. It one tries to initiate it while the daemon is already running, this is the result:

lockfile.LockTimeout: Timeout waiting to acquire lock for /tmp/thedaemon.pid

Of course the cron job doesn't care - it could keep dry-firing the command routinely so that in the case it is not running, it then starts running. But that is not very elegant.

More elegantly, is there a way to set up the cron job to know if the daemon is running before initiating it? Perhaps a short-hand if-condition?

In short, how do I set up the cron job to ensure that the daemon is running?

If running, do nothing. If not running, initiate.

3
  • What exactly do you want to achieve? Do you want a system to automatically restart a crashed daemon? Does the daemon actually have to be run from a cron job? Can't it be run from an init script? Commented Jun 21, 2015 at 16:04
  • 1
    Why do you need to run the daemon from cron instead of init (sysv init/systemd/upstart/...)? Commented Jun 21, 2015 at 18:37
  • Cron in case something happens. Yes, a system upstart too. Basically - always run it :D Commented Jun 21, 2015 at 19:59

1 Answer 1

4

You can wrap your python daemon in a shell script. When you first initiate, check if the process is already running:

pid=$(cat pid.file)
ps -ef | grep $pid | grep <command to start daemon>
if [[ $? -eq 0 ]]; then
    echo "daemon already running" & exit 1
else
    <command to start daemon> & \
             echo $! > pid.file
fi

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.