Running a script every second

Yan Seiner yan at seiner.com
Thu Mar 6 14:13:41 UTC 2014


On 03/05/2014 10:07 AM, Laurent Bercot wrote:
> On 2014-03-05 17:40, Yan Seiner wrote:
>>> I am trying to run a script every second.  I set up two scripts:
>
>  Very dumb question: if your script execution time is much smaller
> than one second, why not simply "while true ; do update ; sleep 1 ; 
> done" ?
> (Or better, "update ; exec sleep 1" in a runit/s6/... run script.)
>
>  If your script execution time is not negligible compared to one second,
> you could replace "update" with "update &".
>  If "update"'s execution time can go over one second, then you need to 
> make
> it reentrant, but it's the same with your SIGHUP and fifo system.
>
Given the constraints I have (which I left out of the original post) 
it's not a dumb question.

1.  update has to run 60 times a minute.  It's not critical that it run 
every second to the millisecond, but it does have to run 60 times a 
minute.  A solution using "sleep" would not work since it takes a real 
and variable time to run update (between .2 and .5 seconds), and sleep 
is not guaranteed to take exactly 1 second.

2.  update is stateful; it compares the state at its last execution with 
the current state.  For that reason spawning update & will not work 
without a lot of overhead.

2.a) If I was to spawn it, I'd use watch -n 1 update and then I'd be done.

3.  Overhead - I am working with a very limited board with low CPU 
power.  Spawning a process every second adds about 2-3% cpu load.

I went to fairly great lengths to build this script with shell builtins 
rather than spawning processes.  I could (and probably will) rewrite 
this in C, but for now it's become an interesting exercise in shell 
scripting.  And learning something is never dumb.

This does, however, raise the question about watch - does it use sleep 
or does it actually trigger it every second?  Time to look at code.


More information about the busybox mailing list