Class: Rapns::Daemon::InterruptibleSleep

Inherits:
Object
  • Object
show all
Defined in:
lib/rapns/daemon/interruptible_sleep.rb

Instance Method Summary collapse

Constructor Details

#initializeInterruptibleSleep



5
6
7
# File 'lib/rapns/daemon/interruptible_sleep.rb', line 5

def initialize
  @sleep_reader, @wake_writer = IO.pipe
end

Instance Method Details

#closeObject



58
59
60
61
62
# File 'lib/rapns/daemon/interruptible_sleep.rb', line 58

def close
  @sleep_reader.close rescue nil
  @wake_writer.close rescue nil
  @udp_wakeup.close if @udp_wakeup rescue nil
end

#enable_wake_on_udp(host, port) ⇒ String, Integer

enable wake on receiving udp packets at the given address and port this returns the host,port used by bind in case an ephemeral port was indicated by specifying 0 as the port number.



13
14
15
16
17
# File 'lib/rapns/daemon/interruptible_sleep.rb', line 13

def enable_wake_on_udp(host, port)
  @udp_wakeup = UDPSocket.new
  @udp_wakeup.bind(host, port)
  @udp_wakeup.addr.values_at(3,1)
end

#interrupt_sleepObject

writing to the pipe will wake the sleeping thread



54
55
56
# File 'lib/rapns/daemon/interruptible_sleep.rb', line 54

def interrupt_sleep
  @wake_writer.write('.')
end

#sleep(timeout) ⇒ boolean

wait for the given timeout in seconds, or data was written to the pipe or the udp wakeup port if enabled.



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
# File 'lib/rapns/daemon/interruptible_sleep.rb', line 22

def sleep(timeout)
  read_ports = [@sleep_reader]
  read_ports << @udp_wakeup if @udp_wakeup
  rs, = IO.select(read_ports, nil, nil, timeout) rescue nil

  # consume all data on the readable io's so that our next call will wait for more data
  if rs && rs.include?(@sleep_reader)
    while true
      begin
        @sleep_reader.read_nonblock(1)
      rescue Errno::EWOULDBLOCK, Errno::EAGAIN
      # rescue IO::WaitReadable
        break
      end
    end
  end

  if rs && rs.include?(@udp_wakeup)
    while true
      begin
        @udp_wakeup.recv_nonblock(1)
      rescue Errno::EWOULDBLOCK, Errno::EAGAIN
      # rescue IO::WaitReadable
        break
      end
    end
  end

  !rs.nil? && rs.any?
end