Class: SchedulerJob

Inherits:
ActiveJob::Base
  • Object
show all
Defined in:
app/jobs/scheduler_job.rb

Direct Known Subclasses

ExampleSchedulerJob

Instance Method Summary collapse

Instance Method Details

#handle_error(error, job_class, job_id, &block) ⇒ nil

Method to handle any error raised when performing a job.

Parameters:

  • error (StandardError)

    the raised error.

  • job_class (String)

    the class of the corresponding Job.

  • job_id (String)

    the id of the corresponding Job.

  • &block (Proc)

    extra block to define custom error handling.

Returns:

  • (nil)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'app/jobs/scheduler_job.rb', line 37

def handle_error(error, job_class, job_id, &block)
  if @job.present?
    @job.completed_at = Time.current
    backtrace = error.backtrace.select { |line| line.include?('app') }.join("\n")
    if block_given?
      yield @job, error, backtrace
    else
      @job.error = error.class
      @job.log :error, "#{error.class}: #{error.message}"
      @job.log :error, backtrace
      @job.backtrace = backtrace
      @job.status!(:error)
    end
    @job.save
  else
    raise "Unable to find #{job_class} with id '#{job_id}'."
  end
end

#perform(job_class, job_id, *args, &block) ⇒ nil

Performs job with ActiveJob framework.

Parameters:

  • job_class (String)

    the class of the corresponding Job.

  • job_id (String)

    the id of the corresponding Job.

  • *args (Array)

    additional arguments.

  • &block (Proc)

    extra block to define custom jobs.

Returns:

  • (nil)


14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'app/jobs/scheduler_job.rb', line 14

def perform(job_class, job_id, *args, &block)
  begin
    @job = job_class.constantize.find(job_id)
    @job.executed_at = Time.current
    @job.status!(:running)
    yield @job, *args if block_given?
    @job.completed_at = Time.current
    @job.progress!(100)
    @job.status!(:completed)
  rescue StandardError => error
    handle_error(error, job_class, job_id)
  end
end