Class: Workers::Task

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/workers/task.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers

#concat_e, #log_debug, #log_error, #log_info, #log_warn

Constructor Details

#initialize(options = {}) ⇒ Task

Returns a new instance of Task.


12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/workers/task.rb', line 12

def initialize(options = {})
  @logger = Workers::LogProxy.new(options[:logger])
  @input = options[:input] || []
  @on_perform = options[:on_perform] || raise(Workers::MissingCallbackError, 'on_perform callback is required.')
  @on_finished = options[:on_finished]
  @max_tries = options[:max_tries] || 1
  @state = :initialized
  @tries = 0

  raise Workers::MaxTriesError, 'max_tries must be >= 1' unless @max_tries >= 1

  nil
end

Instance Attribute Details

#exceptionObject (readonly)

Returns the value of attribute exception


7
8
9
# File 'lib/workers/task.rb', line 7

def exception
  @exception
end

#inputObject (readonly)

Returns the value of attribute input


5
6
7
# File 'lib/workers/task.rb', line 5

def input
  @input
end

#max_triesObject (readonly)

Returns the value of attribute max_tries


9
10
11
# File 'lib/workers/task.rb', line 9

def max_tries
  @max_tries
end

#resultObject (readonly)

Returns the value of attribute result


6
7
8
# File 'lib/workers/task.rb', line 6

def result
  @result
end

#stateObject (readonly)

Returns the value of attribute state


8
9
10
# File 'lib/workers/task.rb', line 8

def state
  @state
end

#triesObject (readonly)

Returns the value of attribute tries


10
11
12
# File 'lib/workers/task.rb', line 10

def tries
  @tries
end

Instance Method Details

#failed?Boolean

Returns:

  • (Boolean)

53
54
55
# File 'lib/workers/task.rb', line 53

def failed?
  @state == :failed
end

#runObject


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/workers/task.rb', line 26

def run
  raise Workers::InvalidStateError, "Invalid state (#{@state})." unless @state == :initialized

  @state = :running

  while(@tries < @max_tries && @state != :succeeded)
    @tries += 1

    begin
      @result = @on_perform.call(@input)
      @state = :succeeded
      @exception = nil
    rescue Exception => e
      @state = :failed
      @exception = e
    end
  end

  @on_finished.call(self)

  nil
end

#succeeded?Boolean

Returns:

  • (Boolean)

49
50
51
# File 'lib/workers/task.rb', line 49

def succeeded?
  @state == :succeeded
end