Question
I'd like to be able to run a UNIX command precisely every second over a long time period.
I need a solution, which does not lag behind after a certain time, because of the time the command itself needs for execution. sleep, watch, and a certain python script all failed me in this regard.
On the microcontroller's such as the http://Arduino.cc I'd do that through hardware clock interrupts. I'd like to know whether there is a similar time-precise shell script solution. All the solutions which I found within StackExchange.com, resulted in a noticeable time lag, if run over hours. See details below.
Practical purpose / application
I want to test whether my network connection is continuously up by sending timestamps via nc
(netcat) every 1 second.
Sender:
precise-timestamp-generator | tee netcat-sender.txt | nc $receiver $port
Receiver:
nc -l -p $port > netcat-receiver.txt
After completion, compare the two logs:
diff netcat-sender.txt netcat-receiver.txt
The diffs would be the untransmitted timestamps. From this I would know at what time my LAN / WAN / ISP makes troubles.
Solution SLEEP
while [ true ]; do date "+%Y-%m-%d %H:%M:%S" ; sleep 1; done | tee timelog-sleep.txt
Gets a certain offset over time, as the command within the loop also takes a little time.
Precision
cat timelog-sleep.txt
2012-07-16 00:45:16
[...]
2012-07-16 10:20:36
Seconds elapsed: 34520
wc -l timelog-sleep.txt
Lines in file: 34243
Precision summarized:
- 34520-34243 = 277 timing problems
- 34520/34243 = 1.008 = 0.8 % off
Solution REPEAT PYTHON
Found at: Repeat a Unix command every x seconds forever
repeat.py 1 "date '+%Y-%m-%d %H:%M:%S'" >> timelog-repeat-py.txt
Supposed to avoid the time offset, but fails to do so.
Precision
wc -l timelog-repeat-py.txt
2012-07-16 13:42:44
[...]
2012-07-16 16:45:24
Seconds elapsed: 10960
wc -l timelog-repeat-py.txt
Lines in file: 10859
Precision summarized:
- 10960-10859 = 101 timing problems
- 10960/10859 = 1.009 = 0.9 % off
Solution WATCH
watch -n 1 "date '+%Y-%m-%d %H:%M:%S' >> ~/Desktop/timelog-watch.txt"
Precision
wc -l timelog-watch.txt
2012-07-16 11:04:08
[...]
2012-07-16 13:25:47
Seconds elapsed: 8499
wc -l timelog-watch.txt
Lines in file: 8366
Precision summarized:
- 8499-8366 = 133 timing problems.
- 8499/8366 = 1.016 = 1.6 % off.
nice
the process that sleeps? – Tilo Wiklund Jul 16 '12 at 19:26I would want to be on a realtime system, in a significantly stripped down setup with no one else logged on, or in single user mode.
Probably a better solution is to modify the program in question to do the loop itself, instead of invoking it from another program.
– Hack Saw Jul 16 '12 at 21:34