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