开发者

Ruby next run in X minutes

开发者 https://www.devze.com 2023-04-03 22:35 出处:网络
I have a ruby on rails app, and there is a cron running in the background. The cron job runs every 10 minutes on the 10 minutes, so 9:00, 9:10, 9:20, 9:30 and so o开发者_JAVA技巧n.

I have a ruby on rails app, and there is a cron running in the background. The cron job runs every 10 minutes on the 10 minutes, so 9:00, 9:10, 9:20, 9:30 and so o开发者_JAVA技巧n. In my rails app, I want to show when the cron will next run.

So I will have, "Cron will next run at: 9:20PM"

I just can't figure out how to get this in ruby.

Thanks, Andrew


def next_10_minutes
  nxt = Time.now+(10-Time.now.min%10).minute
  nxt.strftime("%H:%M")
end

next_10_minutes
#=> "00:30"

or little more flexible and monkey patching

class Time
  def self.next_10_minutes
    self.now+(10-Time.now.min%10).minute
  end
end

Time.next_10_minutes.strftime("%H:%M")
#=> "00:40"


This is quite simple:

  • get the current minutes: min = DateTime.now.min
  • round to the upper ten minute:

    nextTick = ((min/10.0).ceil*10)
    
  • print the difference:

    diff = nextTick - min
    hour = DateTime.now.hour
    if nextTick == 60
        nextTick = 0
        hour = (hour + 1) % 24
    end
    print "Next run in #{diff} minutes (at #{hour}:#{nextTick})"
    

Try it here: http://codepad.org/5vxlg6kF


def next_tick(now)
    min10 = ((now.min / 10) + 1)*10
    if min10 == 60
        Time.mktime(now.year, now.month, now.day, now.hour + 1, 0)
    else
        Time.mktime(now.year, now.month, now.day, now.hour, min10)
    end
end

p next_tick(Time.now)
0

精彩评论

暂无评论...
验证码 换一张
取 消