在 X 分钟内开始工作

Start job in X minutes

我正在尝试 运行 执行控制器操作 3 分钟后的作业。

我用 DelayedJob 试过了:

# in my controller

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

并且在 ReminderJob.rb 文件中:

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

然而,当访问索引页面时,我在日志中没有看到任何东西,3 分钟后什么也没有发生。

我做错了什么?是否有另一种推荐的方法来 运行 任务 "in X minutes from now" 而无需使用 sleep

在这种情况下,我会使用 rails' 内置包 ActiveJob。 参见 here how to setup and basic usage. You can use delayed_job as the backend

在你的情况下,这段代码可以工作:

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

和你的工作:

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