Class: ScoutRails::BackgroundWorker

Inherits:
Object
  • Object
show all
Defined in:
lib/scout_rails/background_worker.rb

Overview

Used to run a given task every 60 seconds.

Constant Summary collapse

PERIOD =

in seconds, time between when the worker thread wakes up and runs.

60

Instance Method Summary collapse

Constructor Details

#initializeBackgroundWorker

Returns a new instance of BackgroundWorker.



6
7
8
# File 'lib/scout_rails/background_worker.rb', line 6

def initialize
  @keep_running = true
end

Instance Method Details

#run_onceObject

Runs the task passed to start once.



15
16
17
# File 'lib/scout_rails/background_worker.rb', line 15

def run_once
  @task.call if @task
end

#start(&block) ⇒ Object

Starts running the passed block every 60 seconds (starting now).



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/scout_rails/background_worker.rb', line 20

def start(&block)
  @task = block
  begin
    ScoutRails::Agent.instance.logger.debug "Starting Background Worker, running every #{PERIOD} seconds"
    next_time = Time.now
    while @keep_running do
      now = Time.now
      while now < next_time
        sleep_time = next_time - now
        sleep(sleep_time) if sleep_time > 0
        now = Time.now
      end
      @task.call
      while next_time <= now
        next_time += PERIOD
      end
    end
  rescue
    ScoutRails::Agent.instance.logger.debug "Background Worker Exception!!!!!!!"
    ScoutRails::Agent.instance.logger.debug $!.message
    ScoutRails::Agent.instance.logger.debug $!.backtrace
  end
end

#stopObject



10
11
12
# File 'lib/scout_rails/background_worker.rb', line 10

def stop
  @keep_running = false
end