File: timers.rb

package info (click to toggle)
ruby-celluloid 0.18.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 848 kB
  • sloc: ruby: 7,579; makefile: 10
file content (72 lines) | stat: -rwxr-xr-x 1,462 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/env ruby

$LOAD_PATH.push File.expand_path("../lib", __dir__)
require "celluloid"

class TimerExample
  include Celluloid
  attr_reader :fired, :timer

  def initialize
    @fired = false
    @timer = after(3) { puts "Timer fired!"; @fired = true }
  end
end

#
# Basic timer example
#

actor = TimerExample.new

# The timer hasn't fired yet, so this should be false
puts "Timer hasn't fired yet, so this should be false: #{actor.fired}"

# Even if we wait a second, it still hasn't fired
sleep 1
puts "Timer still shouldn't have fired yet: #{actor.fired}"

# Wait until after the timer should've fired
sleep 2.1
puts "Timer should've fired now: #{actor.fired}"

#
# Cancelling timers
#

actor = TimerExample.new

# The timer hasn't fired yet, so this should be false
puts "Timer hasn't fired yet, so this should be false: #{actor.fired}"

# Cancel the timer, which should prevent it from firing
actor.timer.cancel

# Wait until after the timer should've fired
sleep 3.1
puts "Timer shouldn't have fired because we cancelled it: #{actor.fired}"

class RepeatingTimerExample
  include Celluloid

  def initialize
    @sheep = 0
  end

  def count_sheep
    print "<#{self.class.name}> Counting sheep to go to sleep: "
    @timer = every(0.1) do
      @sheep += 1
      print @sheep, " "
    end
  end

  def stop_counting
    @timer.cancel
  end
end

sleepy_actor = RepeatingTimerExample.new
sleepy_actor.count_sheep
sleep 1
sleepy_actor.stop_counting