安排任务在红宝石中每月的15号和最后一天工作

问题描述 投票:2回答:2

我在schedule.rb文件中定义了一个耙任务,该任务将在每月的15号和最后一天的上午8点工作。我只是想确认我是否做对了。请看看并提出建议。

[每个月15日的上午8点运行此任务

every '0 8 15 * *' do
  rake 'office:reminder', environment: ENV['RAILS_ENV']
end

[每个月的最后一天的上午8点运行此任务

every '0 8 28-31 * *' do
  rake 'office:reminder', environment: ENV['RAILS_ENV']
end
ruby-on-rails ruby cron scheduled-tasks whenever
2个回答
0
投票

cron通常不允许指定“每月的最后一天”。但是在Ruby中,您可以简单地使用-1表示月份的最后一天:

Date.new(2020, 2, -1)
#=> Sat, 29 Feb 2020

因此,您不必定义特定日期的单独条目,而是可以定义一个每天上午8点运行的条目,并将这些天作为arguments传递给rake任务:

every '0 8 * * *' do
  rake 'office:reminder[15,-1]', environment: ENV['RAILS_ENV']
end

然后在您的任务中,您可以将这些参数转换为日期对象,并检查它们是否等于今天的日期:

namespace :office do
  task :reminder do |t, args|
    days = args.extras.map(&:to_i)
    today = Date.today
    if days.any? { |day| today == Date.new(today.year, today.month, day) }
      # send your reminder
    end
  end
end

0
投票

由于cron具有非常简单的界面,因此在没有外部帮助的情况下很难向其传达“月的最后一天”之类的概念。但是您可以将逻辑转变为任务:

every '0 8 28-31 * *' do
  rake 'office:end_of_month_reminder', environment: ENV['RAILS_ENV']
end

并且在一个名为office:end_of_month_reminder的新任务中:

if Date.today.day == Date.today.end_of_month.day
  #your task here
else
  puts "not the end of the month, skipping"
end

您仍将拥有第一个月的任务。但是,如果您想将其滚动为一个:

every '0 8 15,28-31 * *' do
  rake 'office:reminder', environment: ENV['RAILS_ENV']
end

并且在您的任务中:

if (Date.today.day == 15) || (Date.today.day == Date.today.end_of_month.day) 
  #your task here
else
  puts "not the first or last of the month, skipping"
end
© www.soinside.com 2019 - 2024. All rights reserved.