将任务安排在 ruby 中的每月 15 日和最后一天工作



我在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

由于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

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

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

因此,您可以定义一个每天上午 8 点运行的条目,并将这些日期作为参数传递给 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

最新更新