【问题标题】:What is the best way to schedule `whenever` task in rails in midnight usa?在美国午夜在 Rails 中安排“无论何时”任务的最佳方式是什么?
【发布时间】:2016-05-05 10:52:35
【问题描述】:

我们有一个 Rails 4 应用程序。 在美国午夜的 Rails 中安排 whenever 任务的最佳方式是什么?

我们需要在一天报告的晚上 11.58pm 发送电子邮件。

我们正在使用tzinfogem

TZInfo::Timezone.get('America/Denver').local_to_utc(Time.parse('11:58pm')).strftime('%H:%M%p')

当时没有发送电子邮件。

【问题讨论】:

    标签: ruby-on-rails-4 cron rake-task whenever


    【解决方案1】:

    这可以解决时区问题,服务器位于 UTC,用户位于另一个时区(夏令时)。定义一个本地操作并在 cronjob 中使用。

    schedule.rb

    require "tzinfo"
    
    def local(time)
      TZInfo::Timezone.get('America/Denver').local_to_utc(Time.parse(time))
    end
    
    every :sunday, at: local("11:58 pm") do
     #your email sending task
    end
    

    希望对你有所帮助。

    【讨论】:

    • 针对此类任务的良好全局工作。已收藏!! :)
    【解决方案2】:

    Rehan 的回答太棒了!在我的用例中,我遇到了一个问题,即时区转换也改变了任务计划的星期几。

    也许有更简单的方法,但这就是我所做的。 我们需要的时区转换只会提前工作日。 如果您的用例需要取消工作日,那么您将需要对其进行编辑,但这应该很容易解决。

    def local(time, est_weekday = nil)
      days = [:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday]
      local_time = Time.parse(time)
      utc_time = TZInfo::Timezone.get('America/New_York').local_to_utc(local_time)
      utc_time_formatted = utc_time.strftime("%I:%M %p")
      if est_weekday && days.include?(est_weekday.downcase.to_sym)
        #extract intended wday for ruby datetime and assign
        weekday_index = days.index(est_weekday.downcase.to_sym)
        #get placeholder wday from desired EST day/time
        temp_est_weekday_index = local_time.wday
        #get placeholder wday from adjusted UTC day/time
        temp_utc_weekday_index = utc_time.wday
        #has the conversion to UTC advanced the wday?
        weekday_advances = temp_utc_weekday_index != temp_est_weekday_index
        #adjust wday index if timezone conversion has advanced weekday
        weekday_index += 1 if weekday_advances
        weekday = days[weekday_index]
        return {time: utc_time_formatted, day: weekday || nil }
      else
        return utc_time_formatted
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2022-10-30
      • 1970-01-01
      • 2013-08-25
      • 2011-09-29
      • 1970-01-01
      • 2016-11-23
      • 1970-01-01
      • 2017-09-03
      • 2011-04-23
      相关资源
      最近更新 更多