Class: RJR::ThreadPoolJob

Inherits:
Object show all
Defined in:
lib/rjr/thread_pool.rb

Overview

Work item to be executed in a thread launched by ThreadPool.

The end user should initialize this class with a handle to the job to be executed and the params to pass to it, then hand the instance off to the thread pool to take care of the rest.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*params, &block) ⇒ ThreadPoolJob

ThreadPoolJob initializer

Parameters:

  • params (Array)

    arguments to pass to the job when it is invoked

  • block (Callable)

    handle to callable object corresponding to job to invoke



32
33
34
35
36
37
# File 'lib/rjr/thread_pool.rb', line 32

def initialize(*params, &block)
  @params = params
  @handler = block
  @being_executed = false
  @timestamp = nil
end

Instance Attribute Details

#handlerObject

Proc to be invoked to perform work



15
16
17
# File 'lib/rjr/thread_pool.rb', line 15

def handler
  @handler
end

#paramsObject

Parameters to pass to handler proc



18
19
20
# File 'lib/rjr/thread_pool.rb', line 18

def params
  @params
end

#threadObject

Thread running the job



27
28
29
# File 'lib/rjr/thread_pool.rb', line 27

def thread
  @thread
end

#time_completedObject

Time job completed, if nil job hasn’t completed yet



24
25
26
# File 'lib/rjr/thread_pool.rb', line 24

def time_completed
  @time_completed
end

#time_startedObject

Time job started, if nil job hasn’t started yet



21
22
23
# File 'lib/rjr/thread_pool.rb', line 21

def time_started
  @time_started
end

Instance Method Details

#completed?Boolean

Return bool indicating if job has completed

Returns:

  • (Boolean)


45
46
47
# File 'lib/rjr/thread_pool.rb', line 45

def completed?
  !@time_started.nil? && !@time_completed.nil?
end

#exec(lock) ⇒ Object

Set job metadata and execute job with specified params.

Used internally by thread pool



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/rjr/thread_pool.rb', line 58

def exec(lock)
  lock.synchronize {
    @thread = Thread.current
    @time_started = Time.now
  }

  @handler.call *@params

  # ensure we do not switch to another job
  # before atomic check expiration / terminate
  # expired threads happens below
  lock.synchronize {
    @time_completed = Time.now
    @thread = nil
  }
end

#expired?(timeout) ⇒ Boolean

Return bool indicating if the job has started but not completed and the specified timeout has expired

Returns:

  • (Boolean)


51
52
53
# File 'lib/rjr/thread_pool.rb', line 51

def expired?(timeout)
  !@time_started.nil? && @time_completed.nil? && ((Time.now - @time_started) > timeout)
end

#started?Boolean

Return bool indicating if job has started

Returns:

  • (Boolean)


40
41
42
# File 'lib/rjr/thread_pool.rb', line 40

def started?
  !@time_started.nil?
end