Class: Sinatra::RunLater::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/sinatra/run-later.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeWorker

Returns a new instance of Worker.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/sinatra/run-later.rb', line 37

def initialize
  @thread = Thread.new {

    # removing this seems to allow it shut down nicely
    # trap :INT do
    #  RunLater::Worker.shutdown
    #  exit
    # end

    loop {
      process_queue
    }
  }
end

Instance Attribute Details

#loggerObject

Returns the value of attribute logger.



35
36
37
# File 'lib/sinatra/run-later.rb', line 35

def logger
  @logger
end

#threadObject

Returns the value of attribute thread.



34
35
36
# File 'lib/sinatra/run-later.rb', line 34

def thread
  @thread
end

Class Method Details

.cleanupObject



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/sinatra/run-later.rb', line 68

def self.cleanup
  begin
    Timeout::timeout 10 do
      loop do
        break unless instance.thread[:running]

        # When run in Passenger, explicitly pass control to another thread
        # which will in return hand over control to the worker thread.
        # However, it doesn't work in Passenger 2.1.0, since it removes
        # all its classes before handing the request over to Rails.

        # Thread.pass if defined?(::Passenger)
      end
    end
  rescue Timeout::Error
    # logger.warn("Worker thread takes too long and will be killed.")
    # logger.flush
    instance.thread.kill
    @worker = RunLater::Worker.new
  end
end

.instanceObject



52
53
54
# File 'lib/sinatra/run-later.rb', line 52

def self.instance
  @worker ||= RunLater::Worker.new
end

.shutdownObject



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/sinatra/run-later.rb', line 56

def self.shutdown
  begin
    Timeout::timeout 10 do
      loop { break unless instance.thread[:running] }
    end
  rescue Timeout::Error
    # logger.error("Worker thread timed out. Forcing shutdown.")
  ensure
    instance.thread.kill
  end
end

Instance Method Details

#process_queueObject



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/sinatra/run-later.rb', line 90

def process_queue
  begin
    while block = RunLater.queue.pop
      Thread.pass
      Thread.current[:running] = true
      block.call
      Thread.current[:running] = false
      # logger.flush
    end
  rescue Exception => e
    # logger.error("Worker thread crashed, retrying. Error was: #{e}")
    # logger.flush
    Thread.current[:running] = false
    retry
  end
end