Run a command at most every X seconds without using cron

Some parts of your infrastructure require monitoring every few seconds, but that’s not what cron is for. In these cases you are better suited with a monitoring daemon running continuously:

#!/bin/bash

SLEEP=10

# the next iteration should be at most 10 seconds after the first one 
NEXT=$(( $(date +%s) + $SLEEP ))

while [ 1 ]; do
  # your tests (you can use timeout here, so if your test is stuck
  # won't block the execution of the next one

  # calc how much time we have before next run
  DELTA=$(( $NEXT - $(date +%s) ))

  # if we have time, let's sleep a bit
  if [ "$DELTA" -gt 0 ]; then
    sleep $DELTA
  fi

  # set values for the next iteration
  NEXT=$(( $(date +%s) + $SLEEP ))
done

You can then monitor the script with monit to make sure its running.

Advertisements

One thought on “Run a command at most every X seconds without using cron

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s