Search code examples
rubyrufus-scheduler

Is there a way with rufus-scheduler to schedule a job every 5 minutes, starting at the completion of the last job run?


So if I have a job that is scheduled to run every 5 minutes, and one time while running it happens to take 4 minutes, I'd like it to still wait 5 minutes til it starts the next time, rather than waiting only 1 minute. Any way to do that with rufus-scheduler?

It doesn't look like this is supported directly, although I could perhaps schedule the job itself at the end of its run. The only issue I have with that is a bootstrapping one. (so if the answer to part 1 is no, then is there a built-in way with rufus-scheduler to handle the bootstrapping case?


Solution

  • Rufus-scheduler supports "interval" jobs.

    They are described in the README: https://github.com/jmettraux/rufus-scheduler/#in-at-every-interval-cron

    require 'rufus-scheduler'
    
    s = Rufus::Scheduler.new
    
    s.interval('5m') do |job|
      puts "Doing it..."
      sleep(rand * 1000)
      puts "done. See you in #{job.interval}."
    end
    
    #s.join
    

    If that's not what you were looking, please do note that, in the case of an "every" job, it's OK to modify the "next_time" in flight, like in:

    require 'rufus-scheduler'
    
    s = Rufus::Scheduler.new
    
    s.every '5m' do |job|
      t = Time.now
      puts "doing the job..."
      # ...
      if Time.now - t > 4 * 60
        job.next_time = Time.now + 1 * 60
      end
      puts "next_time will be #{job.next_time}."
    end
    
    #s.join
    

    That could come in handy as well.

    https://github.com/jmettraux/rufus-scheduler#every-jobs-and-changing-the-next_time-in-flight