On 7/14/06, Ruby Quiz <james / grayproductions.net> wrote:
>         1) Devise an "interesting" definition for sleep which allows negative
>            durations.  Alternately, use one of the definitions given here.
>         2) Write some Ruby code demonstrating behavior which satisfies that
>            definition.  As with the above example, you needn't provide a drop-in
>            replacement for Kernel.sleep.
>

When I read this quiz, it reminded me of the time I was working on a
huge realtime 24/7 distributed unix system. Each machine had a time
daemon keeping it in synch with a central time server. During the
first live tests, my application would occasionally core-dump.  When I
first saw the traces, It looked like either one of my queues was
getting corrupted, or the system time had jumped backward.  The lead
of the services group assured me that it was absolutely impossible
that the daemon could set the clock back.  So I spent 2 long days
inspecting core dumps and trace logs, going through my code line by
line, adding more logging, questioning my sanity.  In the end, I
presented the lead with a stack of logs proving that the time daemon
was infact occasionally setting the clock backward by one second.

That gave me this idea for how to implement negative sleep:
-----
# time_demon.rb
# (only tested on windows)

module Time_Demon
  if RUBY_PLATFORM =~ /(win|w)32$/
    TimeStrFormat = "time %H:%M:%S"
  else
    TimeStrFormat = "date -s %H:%M:%S"
  end

  def sleep sec
    t = Time.now
    t+=sec
    system(t.strftime(TimeStrFormat))
    sec.to_i
  end
end

if __FILE__ == $0
p "the time is #{Time.now}"
sleep 5
p "the time is #{Time.now}"
begin
sleep -5
rescue Exception => ex
  p "caught >>#{ex}<<"
end
p "the time is #{Time.now}"

include Time_Demon
sleep 100
p "the time is #{Time.now}"
sleep -50
p "the time is #{Time.now}"
sleep -50
p "the time is #{Time.now}"
end
-----

-Adam