Class: Cosmos::Sleeper

Inherits:
Object show all
Defined in:
lib/cosmos/utilities/sleeper.rb

Overview

Allows for a breakable sleep implementation using the self-pipe trick See www.sitepoint.com/the-self-pipe-trick-explained/

Instance Method Summary collapse

Constructor Details

#initializeSleeper

Returns a new instance of Sleeper.



24
25
26
27
28
# File 'lib/cosmos/utilities/sleeper.rb', line 24

def initialize
  @pipe_reader, @pipe_writer = IO.pipe
  @readers = [@pipe_reader]
  @canceled = false
end

Instance Method Details

#cancelObject

Break sleeping - Once canceled a sleeper cannot be used again



44
45
46
47
48
49
# File 'lib/cosmos/utilities/sleeper.rb', line 44

def cancel
  if !@canceled
    @canceled = true
    @pipe_writer.write('.')
  end
end

#sleep(seconds) ⇒ Object

Breakable version of sleep

Parameters:

  • seconds

    Number of seconds to sleep

Returns:

  • true if the sleep was broken by someone calling cancel otherwise returns false



34
35
36
37
38
39
40
41
# File 'lib/cosmos/utilities/sleeper.rb', line 34

def sleep(seconds)
  read_ready, _ = IO.select(@readers, nil, nil, seconds)
  if read_ready && read_ready.include?(@pipe_reader)
    return true
  else
    return false
  end
end