How can I make a bash command run periodically
I wanted a way to execute a piece of the script every hour within the bash
script file that runs on crontab every 5 minutes without having to use sleep
or rely fully on crontab. if the TIME_INTERVAL is not met, the script will fail at
the first condition. If the TIME_INTERVAL is met, however the TIME_CONDITION is not
met,the script will fail at second condition. The below script does work hand-in-hand
with crontab - adjust according.
NOTE: touch -m "$0" - This will change modification timestamp of the bash script file.
You will have to create a separate file for storing the last script run time,
if you don't want to change the modification timestamp of the bash script file.
CURRENT_TIME=$(date "+%s")
LAST_SCRIPT_RUN_TIME=$(date -r "$0" "+%s")
TIME_INTERVAL='3600'
START_TIME=$(date -d '07:00:00' "+%s")
END_TIME=$(date -d '16:59:59' "+%s")
TIME_DIFFERENCE=$((${CURRENT_TIME} - ${LAST_SCRIPT_RUN_TIME}))
TIME_CONDITION=$((${START_TIME} <= ${CURRENT_TIME} && ${CURRENT_TIME} <= $END_TIME}))
if [[ "$TIME_DIFFERENCE" -le "$TIME_INTERVAL" ]];
then
>&2 echo "[ERROR] FAILED - script failed to run because of time conditions"
elif [[ "$TIME_CONDITION" = '0' ]];
then
>&2 echo "[ERROR] FAILED - script failed to run because of time conditions"
elif [[ "$TIME_CONDITION" = '1' ]];
then
>&2 touch -m "$0"
>&2 echo "[INFO] RESULT - script ran successfully"
fi