Class: Titan::Thread

Inherits:
Object
  • Object
show all
Defined in:
lib/titan/thread.rb

Overview

Titan::Thread helps you creating daemon threads that are independent from your application. Each Titan::Thread is identified by an id that you can either pass on initialization or that gets created automatically.

Constant Summary collapse

TITAN_FILE =
"#{File.expand_path('~')}/.titan"
@@threads =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, &block) ⇒ Thread

Creates a new daemonized thread



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/titan/thread.rb', line 19

def initialize(options = {}, &block)
  @id   = options[:id] || __id__
  @pid  = Process.fork do
    # ignore interrupts
    Signal.trap('HUP', 'IGNORE')
    # execute the actual programm
    block.call
    # exit the forked process cleanly
    Kernel.exit!
  end

  Process.detach(@pid)
  Thread.add(self)
end

Instance Attribute Details

#idObject

Returns the value of attribute id.



12
13
14
# File 'lib/titan/thread.rb', line 12

def id
  @id
end

#pidObject

Returns the value of attribute pid.



12
13
14
# File 'lib/titan/thread.rb', line 12

def pid
  @pid
end

Class Method Details

.add(thread) ⇒ Object



52
53
54
55
56
57
# File 'lib/titan/thread.rb', line 52

def add(thread)
  load_threads
  @@threads[thread.id] = thread
  save_threads
  thread
end

.allObject

Returns all Titan-managed threads



74
75
76
77
# File 'lib/titan/thread.rb', line 74

def all
  load_threads
  @@threads
end

.find(id) ⇒ Object

Returns a thread that has the given id



62
63
64
65
# File 'lib/titan/thread.rb', line 62

def find(id)
  load_threads
  @@threads[id]
end

.kill(id) ⇒ Object



67
68
69
# File 'lib/titan/thread.rb', line 67

def kill(id)
  find(id).kill
end

.load_threadsObject

Loads threads from the TITAN_FILE



82
83
84
85
# File 'lib/titan/thread.rb', line 82

def load_threads
  return unless File.exists?(TITAN_FILE)
  @@threads = YAML::load(File.open(TITAN_FILE)) || {}
end

.remove_dead_threadsObject

Removes threads that are not living anymore



97
98
99
# File 'lib/titan/thread.rb', line 97

def remove_dead_threads
  @@threads.each_value { |thread| @@threads.delete(thread.id) unless thread.alive? }
end

.save_threadsObject

Saves threads to the TITAN_FILE



90
91
92
# File 'lib/titan/thread.rb', line 90

def save_threads
  File.open(TITAN_FILE, 'w') { |file| file.write(YAML::dump(@@threads)) }
end

Instance Method Details

#alive?Boolean

Returns whether the thread is alive or not

Returns:

  • (Boolean)


44
45
46
47
48
49
# File 'lib/titan/thread.rb', line 44

def alive?
  Process.getpgid(@pid)
  true
rescue Errno::ESRCH
  false
end

#killObject

Kills the daemonized thread



37
38
39
# File 'lib/titan/thread.rb', line 37

def kill
  Process.kill('KILL', @pid)
end