Bash script needed to run every second

I have a few cleanup commands to run for my datacaching scheme. I was thinking a bash script would be an easy way to check if the full clean up job needed to be run. But the cache is very time sensitive, so the check script needs to run every second. What’s the best way to do this?

Crontab only goes down to minutes, which makes sense for most applications.

Can I install a bash script as a background service?

On second though, can I just start it with the & command and make it loop forever with a one second sleep?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The simplest way is watch command. You pass number of seconds to -n option:

 watch -n1 'rand'

Method 2

use sleep . try this while true ; do ./your-script & ; sleep 1; done

Method 3

Using the following shell script (I’ll call it repeat-cleanup.sh), you could repeatedly run your code with a 1-second delay between each execution.

while true; do
  # Your cleanup code here, or execute a script containing said code
  sleep 1
done

Execute it using double-forking:

( ./repeat-cleanup.sh & )

Alternatively, you can skip the script altogether and start it with a one-liner:

( while true; do ./cleanup.sh; sleep 1; done & )

Explanation

Neither method runs the script every second. Instead, they wait a second between each execution of the script. As long as the script doesn’t take more than a few hundred milliseconds, that shouldn’t be an issue.

Double-forking disowns the process, allowing it to keep running even if you close your shell. That won’t work if you simply background the process with &.

I’ve tested both methods with a trivial script on Alpine Linux, and they worked consistently.

Method 4

I am using something like that:

do-the-job;
sleep 1; // wait one second till next run
./script-name &; // run same script again on background

But I don’t know if it is correct 🙂


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x