shaveax
shaveax

Reputation: 478

How to schedule a task automatically with a while loop in bash?

I'm trying to schedule my script to run at two different times and then keep running in the background waiting for the next time that the conditions are met again.

So far I am not able to do it because after that one condition is met this scripts exits automatically:

function schedule {

while :
do
    hour=$(date +"%H") 
    minute=$(date +"%M")

    if [[ "$hour" = "02" && "$minute" = "31" ]]; then
        # run some script
        exec /home/gfx/Desktop/myscript.sh
        wait
        schedule

    elif [[ "$hour" = "02" && "$minute" = "32" ]]; then
        # run some script
        exec /home/gfx/Desktop/myscript.sh
        wait
        schedule
    fi 

done

}

schedule

The script that I execute is the following :

$cat myscript.sh
echo "this a message"

Any idea or comment are welcome, thanks!

Upvotes: 1

Views: 1197

Answers (2)

John Hascall
John Hascall

Reputation: 9416

When you do:

 exec some program
 something else

if the exec works, then the something else will never happen because the script is replaced by what you exec'd

Maybe instead of:

exec /home/gfx/Desktop/myscript.sh
wait
schedule

you want:

/home/gfx/Desktop/myscript.sh &
wait
# schedule  -- don't make a fork bomb

As noted in the comments, & + wait is kind of silly, you probably want:

/home/gfx/Desktop/myscript.sh &
# wait
# schedule

or:

/home/gfx/Desktop/myscript.sh
# wait
# schedule

depending on whether or not you want myscript in the background.

ALSO you should put a sleep in the loop, (maybe sleep(59)) to keep it from looping like a banshee.

You begin to understand the appeal of cron I think (at least for things you don't want to interact with your terminal session).

Upvotes: 2

Tushar Niras
Tushar Niras

Reputation: 3863

Crontabs are best place to put these things.

  • Edit crontab using

    $ crontab -e

  • Add following lines to the files

31 2 * * *  /home/gfx/Desktop/myscript.sh

And save crontab file. Your script will be executed every day 2:31 am

Upvotes: 1

Related Questions