Class: Daemonic::Daemon

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Daemon

Returns a new instance of Daemon.



6
7
8
# File 'lib/daemonic/daemon.rb', line 6

def initialize(options)
  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



4
5
6
# File 'lib/daemonic/daemon.rb', line 4

def options
  @options
end

Instance Method Details

#restart(&block) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
# File 'lib/daemonic/daemon.rb', line 64

def restart(&block)
  ensure_pid_specified
  if running?
    stop
    start(&block)
  else
    puts "Not running. Starting a new worker."
    cleanup_pid_file
    start(&block)
  end
end

#start(&block) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/daemonic/daemon.rb', line 10

def start(&block)
  fail ArgumentError, "No block given" if block.nil?
  if options[:daemonize]
    ensure_pid_specified
    fork do
      at_exit { cleanup_pid_file }
      Process.daemon(true)
      write_pid_file
      block.call
    end
    sleep 0.1
    wait_until(options.fetch(:startup_timeout) { 1 }) { !running? }
    if running?
      puts "The daemon started successfully"
    else
      puts "The daemon did not start properly"
      exit 1
    end
  else
    at_exit { cleanup_pid_file }
    write_pid_file
    block.call
  end
end

#statusObject



35
36
37
38
39
40
41
42
43
44
# File 'lib/daemonic/daemon.rb', line 35

def status
  ensure_pid_specified
  if running?
    puts "Running with pid: #{pid.inspect}"
    exit 0
  else
    puts "Not running. Pid: #{pid.inspect}"
    exit 2
  end
end

#stopObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/daemonic/daemon.rb', line 46

def stop
  ensure_pid_specified
  puts "Stopping"
  if running?
    Process.kill("TERM", pid)
    wait_until(options.fetch(:stop_timeout) { 5 }) { !running? }
    if running?
      puts "Couldn't shut down. Pid: #{pid}"
      exit 1
    else
      puts "Worker shut down."
    end
  else
    puts "Not running. Pid: #{pid.inspect}"
    exit 1
  end
end