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.

3

2 Answers 2

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()
6
  • 1
    Why use all uppercase for normal variables? Commented Feb 14, 2017 at 7:12
  • 1
    @codeforester That is the convention in shell scripts. It makes variables easier to distinguish from commands (which are usually lowercase).
    – JigglyNaga
    Commented Feb 14, 2017 at 9: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
    Commented Feb 14, 2017 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
    Commented Feb 14, 2017 at 12:06
  • @fpmurphy1 Related: unix.stackexchange.com/questions/42847/…
    – Kusalananda
    Commented Feb 14, 2017 at 12:11
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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .