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.

  • 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?
    – user86969
    Jun 21, 2015 at 16:04
  • 1
    Why do you need to run the daemon from cron instead of init (sysv init/systemd/upstart/...)?
    – Wieland
    Jun 21, 2015 at 18:37
  • Cron in case something happens. Yes, a system upstart too. Basically - always run it :D
    – 1Up
    Jun 21, 2015 at 19:59

1 Answer 1


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
    <command to start daemon> & \
             echo $! > pid.file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.