Search code examples
ruby-on-railsbackground-processdelayed-job

Start job in X minutes


I am trying to run a job 3 minutes after a controller's action was executed.

I tried this, with DelayedJob:

# in my controller

def index
  @books = Book.all
  Delayed::Job.enqueue(ReminderJob.new(params[:user_id]))
end

And in the ReminderJob.rb file:

class ReminderJob < Struct.new(:user_id)
  def perform
    p "run reminder job"
    # do something
  end
  handle_asynchronously :perform, :run_at => Proc.new { 3.minutes.from_now }
end

However, when accessing the index page, I don't see in the logs anything, and 3 minutes later nothing happens.

What did I do wrong ? Is there another recommended way to run a task "in X minutes from now" without using sleep ?


Solution

  • In this case I would use rails' built in package called ActiveJob. See here how to setup and basic usage. You can use delayed_job as the backend.

    In your case this code would work:

    def index
      user = User.find(params[:user_id])
      ReminderJob.set(wait: 3.minutes).perform_later(user)
    end
    

    and your job:

    class ReminderJob < ApplicationJob # assumes you have a /app/jobs/application_job.rb
      def perform(user)
        # do something with the user
      end
    end