首页 > 解决方案 > 在 ruby​​ 中安排任务在每月的 15 日和最后一天工作

问题描述

我在 schedule.rb 文件中定义了一个 rake 任务,在每月的 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-railsrubycronscheduled-taskswhenever

解决方案


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

推荐阅读