Class: OpenC3::Sleeper

Inherits:
Object show all
Defined in:
lib/openc3/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.



27
28
29
30
31
# File 'lib/openc3/utilities/sleeper.rb', line 27

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



48
49
50
51
52
53
54
# File 'lib/openc3/utilities/sleeper.rb', line 48

def cancel
  if !@canceled
    @canceled = true
    @pipe_writer.write('.')
    @pipe_writer.close
  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



37
38
39
40
41
42
43
44
45
# File 'lib/openc3/utilities/sleeper.rb', line 37

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