ruby-on-rails - 在 Rails 中安排 ActiveJob

标签 ruby-on-rails ruby cron scheduled-tasks rails-activejob

我正在做一个天气 API,它将从另一个 API 获取、处理和保存数据。为了获得每日更新(请求 URL 信息、获取 JSON/XML 数据、构建我的数据并将其保存到我的数据库)我认为最合适的方法是使用 ActiveJob。

我想安排作业定期运行。我想要 UNIX cron 或 Java 的 Spring @Scheduled 注释之类的东西。

我在 Stack Overflow( this one ) 上看到了另一个关于调度作业的问题,但它们像 whenever 一样使用外部 gem。我一直在寻找允许在 Rails API ( Backends ) 中执行作业的后端,但似乎没有一个可用的后端允许调度作业。

Rails 框架(第 5 版)中是否有任何东西可以让我做我想做的事?或者我必须使用外部 gem ?

非常感谢。

编辑 如果对任何人有用,这里是工作的架构:

class ImportDailyDataJob < ApplicationJob
  queue_as :default

  def perform(*args)
    # Do something later
  end

  private

  def prepare_request
    # return the request object
  end

  def request_data
    # Get the data from external API.
  end

  def process_data
    # Process the data
  end

  def save_processed_data
    # Saves the data to the database
  end
end

最佳答案

这不是真正的调度,但如果您不需要完全准确的调度,则在某些情况下可以伪造它,即在您的情况下每天运行一次作业:

class WeatherJob < ApplicationJob
  def perform
    reschedule_job

    do_work
  end

  def do_work
    # ...
  end

  def reschedule_job
    self.class.set(wait: 24.hours).perform_later
  end
end

将来使用 ActiveJob 运行的排队作业应该与 DelayedJob 或 Sidekiq 一起使用,可能并非所有事件作业后端都支持?

关于ruby-on-rails - 在 Rails 中安排 ActiveJob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43506632/

相关文章:

mysql - 在大表上运行 ALTER 迁移的建议

ruby - 为什么 Ruby 会针对私有(private)属性抛出警告

shell - 如何在重新启动后自动设置一次 "AT"计划作业

ruby-on-rails - 将rails应用程序部署到heroku,sendgrid电子邮件链接不可行

css - wicked_pdf(使用 wkhtmltopdf)不呈现 Font Awesome 图标

ruby-on-rails - 在 Rails 中出现两次 Flash 消息

ruby - 在 Ruby 中是否有语法 : class << self . .. end 的任何相关应用程序

ruby - 什么!! ruby 的意思?

php cron 作业未运行

ubuntu - 错误,CronJob Ubuntu