0

I need your small help, i have one script which i can not schedule on crontab. But I am using sleep command.

I am facing issue while using sleep command.

My script took 10 or 15 min to complete ( run time) and I use sleep(3600) which means it sleep for another one hour

But my requirement is that my script start at 9:00, 10:00... and so on . Due to my script execution time which i am taking right now 10 min ( it vary), and after that sleep(3600) command ,my script next run start at 10:10 instead of 10:00

Can anyone help me how i can correct it this so that script run at exactly every hour.

2 Answers2

2
#!/bin/bash

function MY_CODE(){
    START_TIME_SECONDS=$(date +%s)
    <your code>
    END_TIME_SECONDS=$(date +%s)
    SCRIPT_RUN_TIME_IN_SECONDS=$((${END_TIME_SECONDS}-${START_TIME_SECONDS}))
    SLEEP_TIME=$((3600-${SCRIPT_RUN_TIME_IN_SECONDS}))
    sleep ${SLEEP_TIME}
}

MY_CODE()
Kamaraj
  • 4,365
  • 1
    Why use all uppercase for normal variables? – codeforester Feb 14 '17 at 07:12
  • 1
    @codeforester That is the convention in shell scripts. It makes variables easier to distinguish from commands (which are usually lowercase). – JigglyNaga Feb 14 '17 at 09:42
  • @JigglyNaga No, the convention is to use upper-case for environment variables, i.e. exported shell variables. Using uppercase like this makes it hard to read. – Kusalananda Feb 14 '17 at 10:42
  • @Kusalananda. There is no universally agreed upper/lower case convention on shell script variable names other then for certain environment values which are documented in various standards and specifications. – fpmurphy Feb 14 '17 at 12:06
  • @fpmurphy1 Related: http://unix.stackexchange.com/questions/42847/are-there-naming-conventions-for-variables-in-shell-scripts – Kusalananda Feb 14 '17 at 12:11
  • @Kusalananda. Yes, lots of different organizations have produced coding and style guides for Bash and lots more. That is because there is no one agreed convention. – fpmurphy Feb 16 '17 at 10:29
0

Since your objective is to schedule execution based on start time, you can schedule each script execution like this:

#!bin/bash

function runattime {
    execution_time=$1
    delay=$(( $(date -d "$1" "+%s") - $(date "+%s") ))
    if [ $delay -le 0 ]; then
        echo "negative delay, probably due to incorrect date argument"
    else
        sleep $delay && ${@:2}
    fi
}


# One shot run
runattime 11:50 echo blah & 
runattime 11:51 echo bleh & 


# Everyday run
while true; do
    runattime 11:50 echo hola & 
    runattime 11:51 echo hello & 
    sleep 86400  # wait for next day and loop
done

To have the script run in the background even when you are disconnected you can use the nohup command from bash.

pixelou
  • 183