Timer Class

Hai Dude

I want to write one class that class should act as a Timer
On that class , i will check the database every second for database
field called Diaplay_time ,if the current system time matched with
database Display_Time field data then i will show the message in
console,That class should terminate only when i press “Ctrl+C” key
otherwise that wont stop
ok
can any body tell me the solution?
I need to do that
ok
Bye
By
P.S.Hussain

Hi Alex,

On 4/27/07, Alex Y. [email protected] wrote:

You can write a very simple while loop for this:
def time_block

After seeing this code, I thought, how we can make this reentrant.
Here is what I could come up with.

def time_block
start_time = Time.now
Thread.new { yield }
Time.now - start_time
end

def repeat_every(seconds)
while true do
time_spent = time_block { yield } # To handle -ve sleep interaval
sleep(seconds - time_spent) if time_spent < seconds
end
end

repeat_every(1) {
puts “Task started. #{Time.now}”
sleep(2)
puts “Task done. #{Time.now}”
}

What precautions should one take in such code involving threads and
sleep?

Use it like this:

repeat_every(1.0) do

do database stuff

end


Alex

-|[Siddharth] [S] [Karandikar]|-
www.paahijen.com - Applications in Indian Languages!

Imgur

Hussain wrote:

Hai Dude

I want to write one class that class should act as a Timer
On that class , i will check the database every second for database
field called Diaplay_time ,if the current system time matched with
database Display_Time field data then i will show the message in
console,That class should terminate only when i press “Ctrl+C” key
otherwise that wont stop

You can write a very simple while loop for this:

while true do
start_time = Time.now
#do database stuff
total_time = Time.now - start_time
sleep(1.0 - total_time) # ignoring the possibility of total_time > 1
end

Alternatively, to make it more Rubyish, use a block or two (untested):

def time_block
start_time = Time.now
yield
return Time.now - start_time
end

def repeat_every(seconds)
while true do
sleep( seconds - time_block { yield } ) # again ignoring time >
seconds
end
end

Use it like this:

repeat_every(1.0) do

do database stuff

end

On Fri, Apr 27, 2007 at 04:19:18PM +0900, Hussain wrote:

I need to do that
In general there are two common approaches:

  • use threads
  • use an event loop

In Ruby, threads are easy to write. To set up a timer using threads,
create a thread that sleeps for one second, wakes up, then does your
check. The disadvantage to this approach is that your code must be
thread-safe.

With an event loop, your code waits for an event (a timer to fire, input
from the user, etc.) and responds to that event. There are numerous
libraries out there to help with this, including Ruby/Event and
IO::Reactor.

Paul