【问题标题】:Sidekiq to perform action for last month and end of current monthSidekiq 执行上个月和本月末的操作
【发布时间】:2017-03-11 16:15:55
【问题描述】:

我脑子里有这个逻辑,但很难写进代码;我可以但不确定何时使用 Sidekiq 执行此操作

比较上个月的费用和本月的费用(本日历月末)

工人阶级:

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个月内执行,我觉得这是不正确的。是吗?

【问题讨论】:

    标签: ruby-on-rails ruby date sidekiq


    【解决方案1】:

    首先,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 号。

    【讨论】:

    • 谢谢。我已经研究过 cron 但如何传递 args 就像将呼叫移动到 CompareExpenseWorker 的位置一样?我也通过了user_id
    • 好吧,如果是按用户操作,则可以使用 cron 循环遍历所有用户(自动模式)或按需(如您当前正在执行的操作)来完成。我已经更新一个答案。
    • Cron 任务。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多