Sidekiq 执行上个月和本月底的操作

Sidekiq to perform action for last month and end of current month

我脑子里有这个逻辑,但很难写成代码;我可以但不确定何时使用 Sidekiq

执行此操作

Compare last month's expenses with this month's expenses (end of this calendar month)

工人Class:

def perform(*args) # params left out for this example
  [...]
  last_month = user.expenses.where(date: 1.month.ago) # ie Jan
  this_month = user.expenses.where(date: Date.today.at_beginning_of_month..Date.today.end_of_month) # ie Feb (end of Feb)

  # Then my if else here
end

控制器:

CompareExpenseWorker.perform_in(...)

我卡在那里了。这个应该什么时候执行? 1 或 2 个月后?

我觉得我的思想在跟我玩游戏。如果我在 1 个月内执行,我只会得到上个月而不是当前月份(完整日历月)。如果在2个月内进行,我觉得那是不正确的。是吗?

首先,last_month 的计算应该是:

# last_month = user.expenses.where(date: 1.month.ago) # incorrect
last_month = user.expenses.where(
  date: 1.month.ago.beginning_of_month..1.month.ago.end_of_month)

我认为,应该改变整个逻辑。如果你想比较两个完整的月份,应该这样做:

month_2 = user.expenses.where( # e.g. Feb
  date: 2.month.ago.beginning_of_month..2.month.ago.end_of_month)
month_1 = user.expenses.where( # e.g. Mar
  date: 1.month.ago.beginning_of_month..1.month.ago.end_of_month)
# run at any day in April, to compare two full months
# user_id is the id of the user to build reports for
CompareExpenseWorker.perform(user_id)

此外,我认为对 CompareExpenseWorker 的调用不应该放入控制器中,使用 cronjob,安排在每个月的 1 号。