Class: RJR::ThreadPoolJob

Inherits:
Object show all
Defined in:
lib/rjr/util/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



34
35
36
37
38
39
# File 'lib/rjr/util/thread_pool.rb', line 34

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



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

def handler
  @handler
end

#paramsObject

Parameters to pass to handler proc



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

def params
  @params
end

#threadObject

Thread running the job



29
30
31
# File 'lib/rjr/util/thread_pool.rb', line 29

def thread
  @thread
end

#time_completedObject

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



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

def time_completed
  @time_completed
end

#time_startedObject

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



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

def time_started
  @time_started
end

Instance Method Details

#completed?Boolean

Return bool indicating if job has completed

Returns:

  • (Boolean)


47
48
49
# File 'lib/rjr/util/thread_pool.rb', line 47

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



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

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)


53
54
55
# File 'lib/rjr/util/thread_pool.rb', line 53

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)


42
43
44
# File 'lib/rjr/util/thread_pool.rb', line 42

def started?
  !@time_started.nil?
end