【问题标题】:Run a rask task on first and third monday of every month in ruby在每个月的第一个和第三个星期一在 ruby​​ 中运行一个 rask 任务
【发布时间】:2020-05-14 06:09:10
【问题描述】:

我已经定义了一个 rake 任务,但我不确定如何让它在 Ruby 中每个月的第一个和第三个星期一运行。请帮帮我。

schedule.rb

#run this task on every 1st and 3rd monday of the month

  rake 'office:reminder', environment: ENV['RAILS_ENV']

office.rake

namespace :office do
  desc "reminder emails"
  task reminder: :environment do
      PaymentReminderWorker.perform_async(arg1, arg2)
  end
end

请帮我弄清楚。

忘记了第一个星期一我在想这样的事情。

require 'date'
Date.today.mday <= 7

更新的答案(这是一个好方法吗?)

namespace :office do
  desc "reminder emails"
  task reminder: :environment do
   today_date = DateTime.now
   first_monday = Chronic.parse("1st monday of this month", :now => today_date.to_date.beginning_of_month)
   third_monday = Chronic.parse("3rd monday of this month", :now => today_date.to_date.beginning_of_month)
   if today_date == first_monday || today_date == third_monday
     PaymentReminderWorker.perform_async(arg1, arg2)
   end
  end
end

【问题讨论】:

  • 你不能为此写一个crontab schedule吗?
  • @tadman 你的意思是什么时候?
  • @tadman 我在我的问题中添加了一个答案部分。请看一看。
  • 值得测试一下,看看它是否有效。我喜欢做的一件事是有一个我可以使用的日期覆盖变量,比如now = ENV['AT'] ? DateTime.parse(ENV['AT']) : DateTime.now,这样你就可以像NOW=2020-02-29 rake office:reminder那样进行测试,这样你就可以快速跳过实验。

标签: ruby-on-rails ruby rake


【解决方案1】:

你可以这样做:

namespace :office do
  desc "reminder emails"
  task reminder: :environment do
   if (Date.today.monday?) & ((Date.today.mday.in? (1..7)) || (Date.today.mday.in? (15..22)))
     PaymentReminderWorker.perform_async(arg1, arg2)
   end
  end
end

或者只使用没有日期部分的常规任务,在 cron 中它会是:

every '0 0 0 ? * 2#1 *' do
  rake 'office:reminder', environment: ENV['RAILS_ENV']
end

every '0 0 0 ? * 2#3 *' do
  rake 'office:reminder', environment: ENV['RAILS_ENV']
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多