Skip to content

Instantly share code, notes, and snippets.

@mtrunkat
Last active June 12, 2017 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtrunkat/1f79ffc69370385199aa32ddd7ebe98a to your computer and use it in GitHub Desktop.
Save mtrunkat/1f79ffc69370385199aa32ddd7ebe98a to your computer and use it in GitHub Desktop.
Run bash script forever with CRON with concurrency 1
#!/bin/bash
# Original: http://bencane.com/2015/09/22/preventing-duplicate-cron-job-executions/
#
# This script executes ./cmd_loop.sh and save process ID (PID) in file ./forever.pid.
# Everytime it's executed it checks for PID in ./forever.pid and if process is still
# running then exists with nonzero code. Otherwise it executes ./cmd_loop.sh.
PIDFILE=./forever.pid
if [ -f $PIDFILE ]
then
PID=$(cat $PIDFILE)
ps -p $PID > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo "Process already running"
exit 1
else
echo "Process not found assume not running"
echo $$ > $PIDFILE
if [ $? -ne 0 ]
then
echo "Could not create PID file"
exit 1
fi
fi
else
echo $$ > $PIDFILE
if [ $? -ne 0 ]
then
echo "Could not create PID file"
exit 1
fi
fi
echo "Executing cmd_loop.sh"
./cmd_loop.sh
rm $PIDFILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment