Class: Procrastinator::Task

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/procrastinator/task.rb

Overview

Wraps a task handler and task metadata

Direct Known Subclasses

LoggedTask

Defined Under Namespace

Classes: AttemptsExhaustedError, ExpiredError

Constant Summary collapse

TIME_FIELDS =

Fields that store time information

[:run_at, :initial_run_at, :expire_at, :last_fail_at].freeze

Instance Method Summary collapse

Constructor Details

#initialize(metadata, handler) ⇒ Task

Returns a new instance of Task.



22
23
24
25
# File 'lib/procrastinator/task.rb', line 22

def initialize(, handler)
    = 
   @handler  = handler
end

Instance Method Details

#fail(error) ⇒ Object

Records a failure in metadata and attempts to run the handler’s #fail hook if present.

Parameters:

  • error (StandardError)
    • the error that caused the failure



50
51
52
53
54
55
# File 'lib/procrastinator/task.rb', line 50

def fail(error)
   hook = .failure(error)

   try_hook(hook, error)
   hook
end

#runObject Also known as: call

Executes the Task Handler’s #run hook and records the attempt.

If the #run hook completes successfully, the #success hook will also be executed, if defined.

Raises:

  • (ExpiredError)

    when the task run_at is after the expired_at.

  • (AttemptsExhaustedError)

    when the task has been attempted more times than allowed by the queue settings.



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/procrastinator/task.rb', line 33

def run
   raise ExpiredError, "task is over its expiry time of #{ @metadata.expire_at.iso8601 }" if .expired?

   .add_attempt
   result = Timeout.timeout(queue.timeout) do
      @handler.run
   end
   .clear_fails

   try_hook(:success, result)
end

#to_sString

Convert the task into a human-legible string.

Returns:

  • (String)

    Including the queue name, id, and serialized data.



67
68
69
# File 'lib/procrastinator/task.rb', line 67

def to_s
   "#{ @metadata.queue.name }##{ id } [#{ serialized_data }]"
end

#try_hook(method, *params) ⇒ Object

Attempts to run the given optional event hook on the handler, catching any resultant errors to prevent the whole task from failing despite the actual work in #run completing.



59
60
61
62
63
# File 'lib/procrastinator/task.rb', line 59

def try_hook(method, *params)
   @handler.send(method, *params) if @handler.respond_to? method
rescue StandardError => e
   warn "#{ method.to_s.capitalize } hook error: #{ e.message }"
end