在每个月的第一和第三个星期一,在ruby中运行rask任务

问题描述 投票:0回答:1

我已经定义了一个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
ruby-on-rails ruby rake
1个回答
0
投票

您可以做类似的事情:

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
© www.soinside.com 2019 - 2024. All rights reserved.