Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 74 lines (53 sloc) 1.835 kb
df5aaba @tarcieri Initial commit
tarcieri authored
1 Timers
2 ======
64e7309 @tarcieri Better build status image URL
tarcieri authored
3 [![Build Status](https://secure.travis-ci.org/tarcieri/timers.png?branch=master)](http://travis-ci.org/tarcieri/timers)
df5aaba @tarcieri Initial commit
tarcieri authored
4
5 Pure Ruby timer collections. Schedule several procs to fire after configurable
6 delays or at periodic intervals.
7
8 This gem is especially useful when you are faced with an API that accepts a
9 single timeout but you want to run multiple timers on top of it. An example of
10 such a library is [nio4r](https://github.com/tarcieri/nio4r), a cross-platform
11 Ruby library for using system calls like epoll and kqueue.
12
13 Usage
14 -----
15
16 Create a new timer group with `Timers.new`:
17
18 ```ruby
86280ea @tarcieri Add require info to README
tarcieri authored
19 require 'timers'
20
df5aaba @tarcieri Initial commit
tarcieri authored
21 timers = Timers.new
22 ```
23
24 Schedule a proc to run after 5 seconds with `Timers#after`:
25
26 ```ruby
27 five_second_timer = timers.after(5) { puts "Take five" }
28 ```
29
30 The `five_second_timer` variable is now bound to a Timers::Timer object. To
31 cancel a timer, use `Timers::Timer#cancel`
32
33 Once you've scheduled a timer, you can wait until the next timer fires with `Timers#wait`:
34
35 ```ruby
36 # Waits 5 seconds
c6d2e17 @tarcieri Whitespace fixups
tarcieri authored
37 timers.wait
df5aaba @tarcieri Initial commit
tarcieri authored
38
39 # The script will now print "Take five"
40 ```
41
42 You can schedule a block to run periodically with `Timers#every`:
43
44 ```ruby
45 every_five_seconds = timers.every(5) { puts "Another 5 seconds" }
46
47 loop { timers.wait }
48 ```
49
50 If you'd like another method to do the waiting for you, e.g. `Kernel.select`,
51 you can use `Timers#wait_interval` to obtain the amount of time to wait. When
52 a timeout is encountered, you can fire all pending timers with `Timers#fire`:
53
54 ```ruby
55 loop do
56 interval = timers.wait_interval
57 ready_readers, ready_writers = select readers, writers, nil, interval
58
59 if ready_readers || ready_writers
60 # Handle IO
61 ...
62 else
63 # Timeout!
64 timers.fire
65 end
66 end
67 ```
68
69 License
70 -------
71
72 Copyright (c) 2012 Tony Arcieri. Distributed under the MIT License. See
86280ea @tarcieri Add require info to README
tarcieri authored
73 LICENSE for further details.
Something went wrong with that request. Please try again.