Ruby on rails 如何在ruby中运行周期作业?
例如,我有一个想要定期运行的作业(假设我有一个名为Ruby on rails 如何在ruby中运行周期作业?,ruby-on-rails,ruby,Ruby On Rails,Ruby,例如,我有一个想要定期运行的作业(假设我有一个名为period的参数,并且该作业正在计算日志总数): 那么我如何才能做到这一点呢?我是ruby的新手,任何答案都将受到欢迎。这里是一个非常简单和粗糙的每4秒一次的工作示例 如果您使用的是Rails,那么可以将环境添加到普通脚本中并检查时间 #!/bin/env ruby # If this file __FILE in the Rails # project root directory require './config/environmen
period
的参数,并且该作业正在计算日志总数):
那么我如何才能做到这一点呢?我是ruby的新手,任何答案都将受到欢迎。这里是一个非常简单和粗糙的每4秒一次的工作示例 如果您使用的是Rails,那么可以将环境添加到普通脚本中并检查时间
#!/bin/env ruby
# If this file __FILE in the Rails
# project root directory
require './config/environment'
job = -> (seconds, timer) {
puts <<-MSG
Seconds #{seconds} Timer #{timer}
Users #{User.count} # Rails models
Is it beginning of month #{Time.now.beginning_of_month}" # Rails helpers
MSG
}
timer = ARGV.first
loop do
seconds = Time.now.sec
if (seconds % timer.to_i).zero?
job.call(seconds, timer)
end
sleep 1
end
#/bin/env红宝石
#如果这个文件在Rails中
#项目根目录
需要“./config/environment”
作业=->(秒,计时器){
您是否签出过?是的,我尝试过无论何时
,但我如何通过使用原始的ruby
代码来实现这一点?似乎无论何时
对我们来说都太重了如果您只需要上面列出的内容,并且您的应用程序在Unix/Linux环境下运行,为什么不尝试一下cron
呢?有什么问题吗?我们想知道要将它嵌入到源代码中,我们不使用cron
!当不适合我们时,这里没有类似cron
的东西,或者在我的回答中,仔细检查它。抱歉。如果我在2017-07-17 16:32:00
运行脚本,时间是一个小时,那么它应该在2017-07-17:32:00
,但是什么呢我想要的是2017-07-17 17:00:00
,那么如何实现呢
$> vim whenever.rb
#!/bin/env ruby
job = -> (seconds, timer) {
puts "Seconds #{seconds} Timer #{timer}"
}
timer = ARGV.first
loop do
seconds = Time.now.sec
if (seconds % timer.to_i).zero?
job.call(seconds, timer)
end
sleep 1
end
$chmod +x whenever.rb
$ ./whenever.rb 4
Seconds 28 Timer 4
Seconds 32 Timer 4
Seconds 36 Timer 4
^C./whenever.rb:13:in `sleep': Interrupt
#!/bin/env ruby
# If this file __FILE in the Rails
# project root directory
require './config/environment'
job = -> (seconds, timer) {
puts <<-MSG
Seconds #{seconds} Timer #{timer}
Users #{User.count} # Rails models
Is it beginning of month #{Time.now.beginning_of_month}" # Rails helpers
MSG
}
timer = ARGV.first
loop do
seconds = Time.now.sec
if (seconds % timer.to_i).zero?
job.call(seconds, timer)
end
sleep 1
end