Module: Rage::Deferred

Defined in:
lib/rage/deferred/deferred.rb

Overview

Rage::Deferred is an in-process background task queue with at-least-once delivery guarantee that allows you to schedule tasks to be executed later. It can be used to offload long-running operations, such as sending emails or communicating with external APIs.

To schedule a task, first define a task class that includes Rage::Deferred::Task and implements the #perform method.

class SendWelcomeEmail
  include Rage::Deferred::Task

  def perform(email)
    # logic to send the welcome email
  end
end

Then, push the task to the deferred queue:

SendWelcomeEmail.enqueue(email: user.email)

You can also specify a delay for the task execution using the delay option:

SendWelcomeEmail.enqueue(email: user.email, delay: 10) # execute after 10 seconds

Or you can specify a specific time in the future when the task should be executed:

SendWelcomeEmail.enqueue(email: user.email, delay_until: Time.now + 3600) # execute in 1 hour

Defined Under Namespace

Modules: Backends, Task Classes: DeadTask, DeadTaskContextDeserializationError, DeadTasks, DeadTasksLockTimeout, Metadata, MiddlewareChain, Proxy, PushTimeout, Queue

Class Method Summary collapse

Class Method Details

.dead_tasks ⇒ Rage::Deferred::DeadTasks

Return the collection of tasks that Rage no longer retries.

The method returns the same collection object on each call. The collection uses the same backend object as the deferred queue.

Examples:

List dead tasks

Rage::Deferred.dead_tasks.each do |task|
  puts "#{task.id}: #{task.exception_message}"
end

Find one dead task

task = Rage::Deferred.dead_tasks.find_by_id("1735689600-12345-1")

Returns:



68
69
70
# File 'lib/rage/deferred/deferred.rb', line 68

def self.dead_tasks
  @__dead_tasks ||= Rage::Deferred::DeadTasks.new(__backend)
end

.wrap(instance, delay: nil, delay_until: nil) ⇒ Object

Push an instance to the deferred queue without including the Rage::Deferred::Task module.

Examples:

Schedule an arbitrary method to be called in the background

class SendWelcomeEmail < Struct.new(:email)
  def call
  end
end

email_service = SendWelcomeEmail.new(email: user.email)
Rage::Deferred.wrap(email_service).call

Parameters:

  • instance (Object) —

    the instance to wrap

  • delay (Integer, nil) (defaults to: nil) —

    the delay in seconds before the task is executed

  • delay_until (Time, nil) (defaults to: nil) —

    the specific time when the task should be executed



50
51
52
# File 'lib/rage/deferred/deferred.rb', line 50

def self.wrap(instance, delay: nil, delay_until: nil)
  Rage::Deferred::Proxy.new(instance, delay:, delay_until:)
end