【问题标题】:Scheduled Jobs and Custom Clock Processes with Clockwork使用 Clockwork 的计划作业和自定义时钟进程
【发布时间】:2014-07-19 12:18:19
【问题描述】:

我正在尝试了解如何使用发条执行自定义代码。这是 Heroku 在其开发中心文档中使用的示例 lib/clock.rb 文件。

require File.expand_path('../../config/boot',        __FILE__)
require File.expand_path('../../config/environment', __FILE__)
require 'clockwork'

include Clockwork

every(4.minutes, 'Queueing interval job') { Delayed::Job.enqueue IntervalJob.new }
every(1.day, 'Queueing scheduled job', :at => '14:17') { Delayed::Job.enqueue ScheduledJob.new }

什么是 IntervalJob 和 ScheduledJob?这些文件应该放在哪里?我想运行可以访问我的数据库记录的自定义作业。

编辑

这是我的/lib/clock.rb

require 'clockwork'
require './config/boot'
require './config/environment'

module Clockwork

  handler do |job|
    puts "Running #{job}"
  end

  every(2.minutes, 'Filtering Streams') { Delayed::Job.enqueue FilterJob.new}
end

这是我的/lib/filter_job.rb

  class FilterJob
    def perform
      @streams = Stream.all

      @streams.each do |stream|
      # manipulating stream properties
      end
    end
   end

我得到错误:

uninitialized constant Clockwork::FilterJob (NameError)
/app/lib/clock.rb:11:in `block in <module:Clockwork>'

【问题讨论】:

    标签: ruby-on-rails heroku scheduled-tasks clockwork


    【解决方案1】:

    您需要执行以下操作:

    首先安装发条gem。

    在你的 lib 文件夹中创建一个clock.rb

    require 'clockwork'
    require './config/boot'
    require './config/environment'
    
    module Clockwork
    
      handler do |job|
        puts "Running #{job}"
      end
    
      every(1.day, 'Creating Cycle', :at => '22:00') { Delayed::Job.enqueue CyclePlannerJob.new}
    end
    

    在示例中,您提供的 IntervalJob 和 ScheduledJob 是延迟作业。发条在指定的时间触发它们。我正在调用 CyclePlannerJob,这就是我的文件的样子。 lib/cycle_planner_job.rb

    class CyclePlannerJob
      def perform
        CyclePlanner.all.each do |planner|
          if Time.now.in_time_zone("Eastern Time (US & Canada)").to_date.send("#{planner.start_day.downcase}?")
            planner.create_cycle
          end
        end
      end
    end
    

    在我的示例中,我每天晚上 10 点运行 CyclePlanner 作业,该作业运行我设置的延迟作业。类似于 Heroku 示例。 请记住,要使用它,您需要在仪表板中的 Heroku 应用程序上设置时钟工作和延迟工作。 你的 Procfile 也应该是这样的。

    worker:  bundle exec rake jobs:work
    clock: bundle exec clockwork lib/clock.rb
    

    如果您有任何问题,请告诉我,如果需要,我可以详细说明。

    【讨论】:

    • 嘿,感谢您的帮助,当我尝试在 Heroku 上运行它时出现错误,我更新了我的问题。我的 procfile 设置和你的一模一样
    • 你用的是什么版本的rails?
    • 从终端运行“clockwork lib/clock.rb”会发生什么
    • 打开你的控制台'rails c'并尝试运行'Delayed::Job.enqueue FilterJob.new'以确保延迟作业设置正确。你的 gem 安装对了吗?
    • 是的,我已经安装了 gem,我仍然得到 NameError: uninitialized constant FilterJob
    【解决方案2】:

    看起来像名称空间问题。将您的 filter_job.rb 移动到模型目录并尝试。

    【讨论】:

      猜你喜欢
      • 2019-08-05
      • 2017-01-18
      • 1970-01-01
      • 2016-08-17
      • 1970-01-01
      • 2021-11-20
      • 2020-09-24
      • 1970-01-01
      • 2019-08-16
      相关资源
      最近更新 更多