Synchronizing script with real world clock

Posted by Frazmi on Sun 12 Oct 2008 02:34 PM — 3 posts, 12,568 views.

#0
I want to display the "real world" time once per minute. I have a simple function that I call using a timer. The function is:
function fn_echotime ()
Note (" RW time is: " .. os.date () )
end

I would like to augment this simple function so that it "holds" until the real world clock hits "00" seconds. So I wrote the following function:

function fn_echotime ()
secs = os.date ("%S")
if secs ~= "00" then
nrsecs = 60 - tonumber(secs)
Note (nrsecs)
require "wait"
wait.make (function ()
Note ("Inside timer")
wait.time (nrsecs)
end)
end

ColourNote ("grey", "darkblue", " RW time is: " .. os.date () .. " ")
end

The two Note functions return expected values. But the timer does not seem to run, as the function never returns :00 as seconds. I'm sure I'm doing something utterly simple to fix, but I'm stumped.

TIA
Australia Forum Administrator #1
The problem here is the asynchronous nature of the way wait.time works.

It actually creates a timer, and that timer resumes the coroutine when the time is up. If you change it to:


wait.make (function ()
  Note ("Inside timer")
  wait.time (nrsecs)
  Note ("time's up!")
end)	


... you will see what I mean. The words "time's up" appear at the correct moment, although your function fn_echotime returns immediately.

Thus, replace the line 'Note ("time's up!")' with whatever you want to do when the minute is completed. (eg. Note (" RW time is: " .. os.date () )).

However to achieve your effect of showing the time once a minute you still need to call it once a minute, so perhaps something like this instead:


function fn_echotime ()
  require "wait"
  wait.make (function ()
    while true do  -- loop forever
      local secs = tonumber (os.date ("%S"))
      if secs > 0 then
        wait.time (60 - secs)  -- wait till exact minute
      end -- if
      ColourNote ("grey", "darkblue", " RW time is: " .. os.date () .. " ")
      wait.time (55)  -- wait almost a minute
    end -- while
  end)	-- wait.make function
end  -- function fn_echotime


The version above will echo the time, on the minute, indefinitely (and you only need to call it once). I wait 55 seconds rather than a minute, in case some other processing takes so long that it misses the occasional minute.


Amended on Mon 13 Oct 2008 05:29 AM by Nick Gammon
#2
* Slaps forehead with palm of hand.

Thanks!