Permalink
Browse files

add "add_timer", "add_periodic_timer" methods + wrap in fiber context

  • Loading branch information...
1 parent 574d71f commit 5c2aa0ec22509102a1e2fda659c1d2cea5cb6d5e @igrigorik committed May 22, 2011
Showing with 49 additions and 3 deletions.
  1. +14 −3 lib/em-synchrony.rb
  2. +35 −0 spec/timer_spec.rb
View
@@ -51,11 +51,22 @@ def self.sync(df)
end
# a Fiber-aware sleep function using an EM timer
- def self.sleep( secs )
+ def self.sleep(secs)
fiber = Fiber.current
- EM::Timer.new(secs) { fiber.resume }
+ EM::Timer.new(secs) { fiber.resume }
Fiber.yield
end
- end
+ def self.add_timer(interval, &blk)
+ EM.add_timer(interval) do
+ Fiber.new { blk.call }.resume
+ end
+ end
+
+ def self.add_periodic_timer(interval, &blk)
+ EM.add_periodic_timer(interval) do
+ Fiber.new { blk.call }.resume
+ end
+ end
+ end
end
View
@@ -0,0 +1,35 @@
+require "spec/helper/all"
+
+describe EventMachine::Synchrony do
+
+ it "should execute one-shot timer in Fiber" do
+ EM.synchrony do
+ start = Time.now.to_f
+
+ EM::Synchrony.add_timer(0.1) do
+ EM::Synchrony.sleep(0.1)
+
+ (Time.now.to_f - start).should > 0.2
+ EventMachine.stop
+ end
+ end
+ end
+
+ it "should execute period timers in Fibers" do
+ EM.synchrony do
+ start = Time.now.to_f
+ num = 0
+
+ EM::Synchrony.add_periodic_timer(0.1) do
+ EM::Synchrony.sleep(0.1)
+ num += 1
+
+ if num > 1
+ (Time.now.to_f - start).should > 0.3
+ EventMachine.stop
+ end
+ end
+ end
+ end
+
+end

0 comments on commit 5c2aa0e

Please sign in to comment.