Threaded Observer

  • Thread starter James Edward Gray II
  • Start date
J

James Edward Gray II

Help Thread gurus! :D

Why is the following code not printing the time every three second the
"Clock" is running, as I believe it should be?

#!/usr/bin/env ruby

require "observer"
require "singleton"

class Clock
include Observable
include Singleton

def start( seconds_delay )
@thread = Thread.new(self, seconds_delay) do |notifier, delay|
loop do
puts "Notifying..."
notifier.notify_observers
sleep delay
end
end
end

def stop
unless @thread.nil?
@thread.kill
@thread = nil
end
end
end

if $0 == __FILE__
class TimePrinter
def update
puts Time.now
end
end

clock = Clock.instance
clock.add_observer TimePrinter.new

puts "Starting clock..."
clock.start 3
sleep 10
clock.stop
puts "Clock stopped..."
sleep 10
end

__END__

Thanks.

James Edward Gray II
 
J

James Edward Gray II

Help Thread gurus! :D

Figures, I got it as soon as I pushed "Send". The correction is below,
for the curious.

Sorry about the noise.

James Edward Gray II
#!/usr/bin/env ruby

require "observer"
require "singleton"

class Clock
include Observable
include Singleton

def start( seconds_delay )
@thread = Thread.new(self, seconds_delay) do |notifier, delay|
loop do
puts "Notifying..."

changed # I often forget this, for some reason.
 
A

Ara.T.Howard

Help Thread gurus! :D

Why is the following code not printing the time every three second the
"Clock" is running, as I believe it should be?

#!/usr/bin/env ruby

require "observer"
require "singleton"

class Clock
include Observable
include Singleton

def start( seconds_delay )
@thread = Thread.new(self, seconds_delay) do |notifier, delay|
loop do
puts "Notifying..."
notifier.notify_observers
sleep delay
end
end
end

def stop
unless @thread.nil?
@thread.kill
@thread = nil
end
end
end

if $0 == __FILE__
class TimePrinter
def update
puts Time.now
end
end

clock = Clock.instance
clock.add_observer TimePrinter.new

puts "Starting clock..."
clock.start 3
sleep 10
clock.stop
puts "Clock stopped..."
sleep 10
end

__END__

Thanks.

James Edward Gray II

it does for me. on linux. are you on windows? if so the IO (puts) is
probably causing the whole process to sleep.

regards.

-a
--
===============================================================================
| EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
| PHONE :: 303.497.6469
| When you do something, you should burn yourself completely, like a good
| bonfire, leaving no trace of yourself. --Shunryu Suzuki
===============================================================================
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top