rubyrufus-scheduler

How to queue rufus-scheduler jobs


I have something like the following:

# myScript.rb

require 'rufus-scheduler'

  def loop
    "hey I am i the loop"
  end 

  def run_schedule(url, count, method, interval)
    puts "running scheduler"

    scheduler = Rufus::Scheduler.new

    scheduler.every interval do

    loop(url, count, method)
    end
  end  

  run_schedule(url, count, method, interval)

My expectation is that when I run:

bundle exec ruby myScript.rb url, count, method, interval

I see output to STD a bunch of "hey I am in the loop" based on the interval.

What happens is I exit to the command line prompt and never see the loop run.


Solution

  • How can you expect

    def loop
      "hey I am i the loop"
    end 
    

    to output anything to stdout (not STD)? It is just returning a string, it is not calling print or puts...

    # myScript.rb
    
    require 'rufus-scheduler'
    
    def _loop(u, c, m)
      # "loop" is a bad name, it's a Ruby keyword, so using "_loop" instead
      # it's still a bad name
    
      p "hey I am i the loop"
      p [ Time.now, [ u, c, m ] ]
        # without p or puts nothing gets to stdout
    end
    
    $scheduler = Rufus::Scheduler.new
      # creating a single scheduler for the whole script
      # not creating a new scheduler each time run_schedule is called
    
    def run_schedule(url, count, method, interval)
    
      #puts "running scheduler"
      #scheduler = Rufus::Scheduler.new
        # commenting out...
    
      $scheduler.every interval do
    
        _loop(url, count, method)
      end
    end
    
    #run_schedule(url, count, method, interval)
    run_schedule('url', 'count', 'method', '3s')
    
    $scheduler.join
      # let the Ruby main thread join the scheduler thread so that
      # the Ruby process does not exit and so scheduling may happen
    

    and so it goes:

    "hey I am i the loop"
    [2017-02-08 06:06:01 +0900, ["url", "count", "method"]]
    "hey I am i the loop"
    [2017-02-08 06:06:05 +0900, ["url", "count", "method"]]
    "hey I am i the loop"
    [2017-02-08 06:06:08 +0900, ["url", "count", "method"]]
    

    Note the $scheduler.join at the end of the script. That prevents the Ruby process from exiting. Since that process doesn't exist, the threads in it (in our case, the thread in the rufus-scheduler instance) live and do their work. Your initial script was simply exiting, freeing all its resources, as expected.