Run scripts as daemon or through cron continuously

by jagbir on February 9, 2012

How to run a script per second? Any easy way to check that no multiple instances of the script will run at a single time? I am cnvering 3 simple ways which helps you to fulfill such requirements:

  1. Using Cron
    If script needs to be executed every x minute or a frequency which is more than a minute, then it should run through cron only. You can also place it in cron when the script itself contains code to execute repeatedly. Make sure to redirect all its logs/errors to some log file for checking in case some issue occurs.
  2. Using Daemon
    If script requires running on frequency less than a minute which is not supported by cron, then a wrapper script acting as daemon can be created to control the execution of our script. This wrapper shell script will run continuously and execute our script at desired internal after verifying that it should not be running already. Means no two instances should run at a time. What if our wrapper script get’s terminated somehow? Put it in inittab which will keep it running always. Let’s take an example.Suppose we need to execute /usr/local/myscripts/example.php every second. Here are the steps you should take to create its wrapper script and start execution:
    1. Create a wrapper shell script with same name as actual script (but with .sh extension), let’s say /root/example.sh:
      $ cat example.sh
      #!/bin/bash
      while [ true ]; do
      sleep 1 ## frequency at which script will be executed
      if [ -z "`ps ax | grep example.php| grep -v grep`"]; then ## do not run more than one instance of script
      `nohup /usr/bin/php /usr/local/myscripts/example.php`
      fi
      done
    2. Put wrapper script entry in inittab to keep it running:
      $ vim /etc/inittab
      # Run xdm in runlevel 5
      ..
      dm:234:respawn:/root/example.sh
      ..
    3. Finally, re-read inittab to start daemon which in result will start our script:

      $ init q

      You can verify by checking processlist that daemon and our scripts are running.
  3. Using hatool
    This is another way to run scripts. We will make use of two external tools: halockrun and hatimerun. halockrun will keep script running and keep a lock file to check avoid multiple instances while with hatimerun we can specify after how much time script can be terminated (because sometimes scripts become stale/defunct).
    Let’s take an example, here’s the example cron entry using these tools:
    * * * * hatimerun -t 300 halockrun -nc /tmp/example.lock /usr/bin/php /usr/local/myscripts/example.php
    In above example, hatimerun will terminate script after 300 ms and halockrun will again execute it keeping lock file to avoid multiple instances.

Previous post:

Next post: