As pointed out by Wiimm his answer only covers the "run the script, wait 10 seconds and repeat, between 8:00 and 12:00".
There are several approaches I can think of:
A. start the script at 8:00 in cron and have it check when it's time to finish
#!/bin/sh
END=$(date -d "12:00" +"%H * 60 + %M" | bc)
while [ $(date +"%H * 60 + %M" | bc) -lt $END ]; do
date >> /tmp/log.txt # replace this with your script
sleep 10
done
Explanation:
date +"%H * 60 + %M" | bc
computes the minutes since the day started. Note: bc is used here to handle leading zeros $(( $(date +"%H * 60 + %M") ))
would error out.
[ $(date +"%H * 60 + %M" | bc) -lt $END ]
- compares with the time to end
B. start it from cron and use a signal handler to handle a graceful exit, use cron to end it.
#!/bin/bash
echo $$ > /tmp/pid.txt
EXIT=
trap "echo 'Exiting' >> /tmp/log.txt; EXIT=yes" TERM
while [[ -z "$EXIT" ]]; do
date >> /tmp/log.txt # replace this with your script
sleep 10
done
crontab would look like this:
00 08 * * * /path/to/wrappers/script.sh
00 12 * * * kill $(cat /tmp/pid.txt)
Explanation:
echo $$ > /tmp/pid.txt
- saves the pid (you should probably chose
another location, appropriate for your system)
trap "echo 'Exiting' >> /tmp/log.txt; EXIT=yes" TERM
- this will run the echo 'Exiting' >> /tmp/log.txt; EXIT=yes
when a TERM
signal is received (TERM is the default signal sent by kill).
while [[ -z "$EXIT" ]]; do
- repeat while EXIT is empty
- this has the advantage of being able to gracefully shut down the script when needed, not only at 12:00.
Note: a combination of both would be probably the best approach.
Also: see https://stackoverflow.com/a/53561843/939457 - it details how to run this via SystemD, but that will run the script every 10 seconds even if the previous script didn't end (if I understand the answer correctly, I'm not familiar with SystemD)