【问题标题】:Schedule a task to work on 15th and the last day of the month in ruby在 ruby​​ 中安排任务在每月的 15 日和最后一天工作
【发布时间】:2020-05-12 23:42:26
【问题描述】:

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

【问题讨论】:

  • 0 8 28-31 * * 将在 28 日、29 日、30 日和 31 日上午 8 点运行该作业。
  • @Stefan 我怎样才能让它在本月的最后一天运行?
  • AFAIK 你不能在 cron 中指定“一个月的最后一天”。一种可能的解决方法是指定0 8 * * *,即每天早上 8 点运行任务并将当天处理移至 rake 任务中。为避免对值进行硬编码,您可以在调用任务时将它们作为参数传递,即 15-1

标签: ruby-on-rails ruby cron scheduled-tasks whenever


【解决方案1】:

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

【讨论】:

  • 从我读到的cron0 0 0 L * ? * 这意味着“本月的最后一天”
  • @Beartech L 是非标准扩展。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多