【问题标题】:Start job in X minutes在 X 分钟内开始工作
【发布时间】:2016-11-28 14:29:23
【问题描述】:

我正在尝试在控制器的操作执行 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 分钟后没有任何反应。

我做错了什么?是否有另一种推荐的方法来“在 X 分钟后”不使用 sleep 运行任务?

【问题讨论】:

  • 为什么不用rails内置的ActiveJob
  • @RaVeN 我找不到任何方法来使用 activeJob 说“在 X 分钟内开始这项工作”。这可能吗?
  • 您可以使用ExampleJob.set(wait: 3.minutes).perform_later(user_id)。我写了一个解释这个解决方案的答案。

标签: ruby-on-rails background-process delayed-job


【解决方案1】:

在这种情况下,我将使用名为 ActiveJob 的 rails 内置包。 请参阅here 如何设置和基本用法。你可以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

【讨论】:

    猜你喜欢
    • 2017-12-01
    • 1970-01-01
    • 2016-09-08
    • 2015-07-15
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 2016-04-17
    相关资源
    最近更新 更多