Search
 
SCRIPT & CODE EXAMPLE
 

SHELL

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
Comment

PREVIOUS NEXT
Code Example
Shell :: ssh delete folders older than one year 
Shell :: Install Deno - PowerShell (Windows) 
Shell :: codeception environnement variable not found 
Shell :: there are stopped jobs 
Shell :: mac end process shortcut 
Shell :: Linux Find word and replace text 
Shell :: Installing gitflow locally 
Shell :: how to pass multiple hosts to ansible adhoc command? 
Shell :: bash change variable in while loop 
Shell :: bat configuration file 
Shell :: apt remove package completely with configuration 
Shell :: Add branch to git prompt ubuntu wsl 
Shell :: calenderfx installation 
Shell :: how to add passphrase to ssh key 
Shell :: git find the commit that introduced a bug 
Shell :: find directory spend inodes 
Shell :: how to uninstall Gnome System Monitor 
Shell :: cant install cython buildozer 
Shell :: how export tables database in command line linux 
Shell :: how to install wine in ubuntu 
Shell :: powershell test-path remote computer 
Shell :: gaussian corrdinates to pdb 
Shell :: install graphene federation 
Shell :: cmd concatenate files 
Shell :: powershell script clear cach at end 
Shell :: Bash script using input to iterate through array 
Shell :: Screen casting to smart screen (DLNA) from ubuntu 
Shell :: remove inkscape older version 
Shell :: install wsl windows 11 
Shell :: restart linux 
ADD CONTENT
Topic
Content
Source link
Name
3+4 =