gpt4 book ai didi

ruby-on-rails - 使用 Clockwork 的计划作业和自定义时钟进程

转载 作者:行者123 更新时间:2023-12-03 16:20:21 26 4
gpt4 key购买 nike

我想了解如何使用发条执行自定义代码。这是 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>'

最佳答案

您需要执行以下操作:

首先安装发条 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

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

关于ruby-on-rails - 使用 Clockwork 的计划作业和自定义时钟进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24840314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com