Giter Site home page Giter Site logo

rufus-scheduler's Introduction

rufus-scheduler

tests Gem Version

Job scheduler for Ruby (at, cron, in and every jobs).

It uses threads.

Note: maybe are you looking for the README of rufus-scheduler 2.x? (especially if you're using Dashing which is stuck on rufus-scheduler 2.0.24)

Quickstart:

# quickstart.rb

require 'rufus-scheduler'

scheduler = Rufus::Scheduler.new

scheduler.in '3s' do
  puts 'Hello... Rufus'
end

scheduler.join
  #
  # let the current thread join the scheduler thread
  #
  # (please note that this join should be removed when scheduling
  # in a web application (Rails and friends) initializer)

(run with ruby quickstart.rb)

Various forms of scheduling are supported:

require 'rufus-scheduler'

scheduler = Rufus::Scheduler.new

# ...

scheduler.in '10d' do
  # do something in 10 days
end

scheduler.at '2030/12/12 23:30:00' do
  # do something at a given point in time
end

scheduler.every '3h' do
  # do something every 3 hours
end
scheduler.every '3h10m' do
  # do something every 3 hours and 10 minutes
end

scheduler.cron '5 0 * * *' do
  # do something every day, five minutes after midnight
  # (see "man 5 crontab" in your terminal)
end

# ...

Rufus-scheduler uses fugit for parsing time strings, et-orbi for pairing time and tzinfo timezones.

non-features

Rufus-scheduler (out of the box) is an in-process, in-memory scheduler. It uses threads.

It does not persist your schedules. When the process is gone and the scheduler instance with it, the schedules are gone.

A rufus-scheduler instance will go on scheduling while it is present among the objects in a Ruby process. To make it stop scheduling you have to call its #shutdown method.

Please note: rufus-scheduler is not a cron replacement.

related gems

similar gems

  • Whenever - let cron call back your Ruby code, trusted and reliable cron drives your schedule
  • Clockwork - rufus-scheduler inspired gem
  • Crono - an in-Rails cron scheduler
  • PerfectSched - highly available distributed cron built on Sequel and more

note about the 3.0 line

It's a complete rewrite of rufus-scheduler.

There is no EventMachine-based scheduler anymore.

I don't know what this Ruby thing is, where are my Rails?

I'll drive you right to the tracks.

notable changes:

  • As said, no more EventMachine-based scheduler
  • scheduler.every('100') { will schedule every 100 seconds (previously, it would have been 0.1s). This aligns rufus-scheduler with Ruby's sleep(100)
  • The scheduler isn't catching the whole of Exception anymore, only StandardError
  • The error_handler is #on_error (instead of #on_exception), by default it now prints the details of the error to $stderr (used to be $stdout)
  • Rufus::Scheduler::TimeOutError renamed to Rufus::Scheduler::TimeoutError
  • Introduction of "interval" jobs. Whereas "every" jobs are like "every 10 minutes, do this", interval jobs are like "do that, then wait for 10 minutes, then do that again, and so on"
  • Introduction of a lockfile: true/filename mechanism to prevent multiple schedulers from executing
  • "discard_past" is on by default. If the scheduler (its host) sleeps for 1 hour and a every '10m' job is on, it will trigger once at wakeup, not 6 times (discard_past was false by default in rufus-scheduler 2.x).
  • Introduction of Scheduler #on_pre_trigger and #on_post_trigger callback points

getting help

So you need help. People can help you, but first help them help you, and don't waste their time. Provide a complete description of the issue. If it works on A but not on B and others have to ask you: "so what is different between A and B" you are wasting everyone's time.

"hello", "please" and "thanks" are not swear words.

Go read how to report bugs effectively, twice.

Update: help_help.md might help help you.

issues

Yes, issues can be reported in rufus-scheduler issues, I'd actually prefer bugs in there. If there is nothing wrong with rufus-scheduler, a Stack Overflow question is better.

faq

scheduling

Rufus-scheduler supports five kinds of jobs. in, at, every, interval and cron jobs.

Most of the rufus-scheduler examples show block scheduling, but it's also OK to schedule handler instances or handler classes.

in, at, every, interval, cron

In and at jobs trigger once.

require 'rufus-scheduler'

scheduler = Rufus::Scheduler.new

scheduler.in '10d' do
  puts "10 days reminder for review X!"
end

scheduler.at '2014/12/24 2000' do
  puts "merry xmas!"
end

In jobs are scheduled with a time interval, they trigger after that time elapsed. At jobs are scheduled with a point in time, they trigger when that point in time is reached (better to choose a point in the future).

Every, interval and cron jobs trigger repeatedly.

require 'rufus-scheduler'

scheduler = Rufus::Scheduler.new

scheduler.every '3h' do
  puts "change the oil filter!"
end

scheduler.interval '2h' do
  puts "thinking..."
  puts sleep(rand * 1000)
  puts "thought."
end

scheduler.cron '00 09 * * *' do
  puts "it's 9am! good morning!"
end

Every jobs try hard to trigger following the frequency they were scheduled with.

Interval jobs trigger, execute and then trigger again after the interval elapsed. (every jobs time between trigger times, interval jobs time between trigger termination and the next trigger start).

Cron jobs are based on the venerable cron utility (man 5 crontab). They trigger following a pattern given in (almost) the same language cron uses.

Chronic and "Wed at 2pm"

By default, rufus-scheduler relies on Ruby to parse strings like "Wed at 2pm". But most of the time, when calling this on Thursday, the day before is "invoked". Relying on Chronic might solve the issue.

Compare

require 'rufus-scheduler'

scheduler = Rufus::Scheduler.new

scheduler.at('Wed at 2pm') do
  # ... might point in the past and thus get triggered immediately
end

with

require 'chronic'
require 'rufus-scheduler'

scheduler = Rufus::Scheduler.new

scheduler.at('Wed at 2pm') do
  # ... will point to a time in the future and trigger appropriately
end

#schedule_x vs #x

schedule_in, schedule_at, schedule_cron, etc will return the new Job instance.

in, at, cron will return the new Job instance's id (a String).

job_id =
  scheduler.in '10d' do
    # ...
  end
job = scheduler.job(job_id)

# versus

job =
  scheduler.schedule_in '10d' do
    # ...
  end

# also

job =
  scheduler.in '10d', job: true do
    # ...
  end

#schedule and #repeat

Sometimes it pays to be less verbose.

The #schedule methods schedules an at, in or cron job. It just decides based on its input. It returns the Job instance.

scheduler.schedule '10d' do; end.class
  # => Rufus::Scheduler::InJob

scheduler.schedule '2013/12/12 12:30' do; end.class
  # => Rufus::Scheduler::AtJob

scheduler.schedule '* * * * *' do; end.class
  # => Rufus::Scheduler::CronJob

The #repeat method schedules and returns an EveryJob or a CronJob.

scheduler.repeat '10d' do; end.class
  # => Rufus::Scheduler::EveryJob

scheduler.repeat '* * * * *' do; end.class
  # => Rufus::Scheduler::CronJob

(Yes, no combination here gives back an IntervalJob).

schedule blocks arguments (job, time)

A schedule block may be given 0, 1 or 2 arguments.

The first argument is "job", it's simply the Job instance involved. It might be useful if the job is to be unscheduled for some reason.

scheduler.every '10m' do |job|

  status = determine_pie_status

  if status == 'burnt' || status == 'cooked'
    stop_oven
    takeout_pie
    job.unschedule
  end
end

The second argument is "time", it's the time when the job got cleared for triggering (not Time.now).

Note that time is the time when the job got cleared for triggering. If there are mutexes involved, now = mutex_wait_time + time...

"every" jobs and changing the next_time in-flight

It's OK to change the next_time of an every job in-flight:

scheduler.every '10m' do |job|

  # ...

  status = determine_pie_status

  job.next_time = Time.now + 30 * 60 if status == 'burnt'
    #
    # if burnt, wait 30 minutes for the oven to cool a bit
end

It should work as well with cron jobs, not so with interval jobs whose next_time is computed after their block ends its current run.

scheduling handler instances

It's OK to pass any object, as long as it responds to #call(), when scheduling:

class Handler
  def self.call(job, time)
    p "- Handler called for #{job.id} at #{time}"
  end
end

scheduler.in '10d', Handler

# or

class OtherHandler
  def initialize(name)
    @name = name
  end
  def call(job, time)
    p "* #{time} - Handler #{name.inspect} called for #{job.id}"
  end
end

oh = OtherHandler.new('Doe')

scheduler.every '10m', oh
scheduler.in '3d5m', oh

The call method must accept 2 (job, time), 1 (job) or 0 arguments.

Note that time is the time when the job got cleared for triggering. If there are mutexes involved, now = mutex_wait_time + time...

scheduling handler classes

One can pass a handler class to rufus-scheduler when scheduling. Rufus will instantiate it and that instance will be available via job#handler.

class MyHandler
  attr_reader :count
  def initialize
    @count = 0
  end
  def call(job)
    @count += 1
    puts ". #{self.class} called at #{Time.now} (#{@count})"
  end
end

job = scheduler.schedule_every '35m', MyHandler

job.handler
  # => #<MyHandler:0x000000021034f0>
job.handler.count
  # => 0

If you want to keep that "block feeling":

job_id =
  scheduler.every '10m', Class.new do
    def call(job)
      puts ". hello #{self.inspect} at #{Time.now}"
    end
  end

pause and resume the scheduler

The scheduler can be paused via the #pause and #resume methods. One can determine if the scheduler is currently paused by calling #paused?.

While paused, the scheduler still accepts schedules, but no schedule will get triggered as long as #resume isn't called.

job options

name: string

Sets the name of the job.

scheduler.cron '*/15 8 * * *', name: 'Robert' do |job|
  puts "A, it's #{Time.now} and my name is #{job.name}"
end

job1 =
  scheduler.schedule_cron '*/30 9 * * *', n: 'temporary' do |job|
    puts "B, it's #{Time.now} and my name is #{job.name}"
  end
# ...
job1.name = 'Beowulf'

blocking: true

By default, jobs are triggered in their own, new threads. When blocking: true, the job is triggered in the scheduler thread (a new thread is not created). Yes, while a blocking job is running, the scheduler is not scheduling.

overlap: false

Since, by default, jobs are triggered in their own new threads, job instances might overlap. For example, a job that takes 10 minutes and is scheduled every 7 minutes will have overlaps.

To prevent overlap, one can set overlap: false. Such a job will not trigger if one of its instances is already running.

The :overlap option is considered before the :mutex option when the scheduler is reviewing jobs for triggering.

mutex: mutex_instance / mutex_name / array of mutexes

When a job with a mutex triggers, the job's block is executed with the mutex around it, preventing other jobs with the same mutex from entering (it makes the other jobs wait until it exits the mutex).

This is different from overlap: false, which is, first, limited to instances of the same job, and, second, doesn't make the incoming job instance block/wait but give up.

:mutex accepts a mutex instance or a mutex name (String). It also accept an array of mutex names / mutex instances. It allows for complex relations between jobs.

Array of mutexes: original idea and implementation by Rainux Luo

Note: creating lots of different mutexes is OK. Rufus-scheduler will place them in its Scheduler#mutexes hash... And they won't get garbage collected.

The :overlap option is considered before the :mutex option when the scheduler is reviewing jobs for triggering.

timeout: duration or point in time

It's OK to specify a timeout when scheduling some work. After the time specified, it gets interrupted via a Rufus::Scheduler::TimeoutError.

scheduler.in '10d', timeout: '1d' do
  begin
    # ... do something
  rescue Rufus::Scheduler::TimeoutError
    # ... that something got interrupted after 1 day
  end
end

The :timeout option accepts either a duration (like "1d" or "2w3d") or a point in time (like "2013/12/12 12:00").

:first_at, :first_in, :first, :first_time

This option is for repeat jobs (cron / every) only.

It's used to specify the first time after which the repeat job should trigger for the first time.

In the case of an "every" job, this will be the first time (modulo the scheduler frequency) the job triggers. For a "cron" job as well, the :first will point to the first time the job has to trigger, the following trigger times are then determined by the cron string.

scheduler.every '2d', first_at: Time.now + 10 * 3600 do
  # ... every two days, but start in 10 hours
end

scheduler.every '2d', first_in: '10h' do
  # ... every two days, but start in 10 hours
end

scheduler.cron '00 14 * * *', first_in: '3d' do
  # ... every day at 14h00, but start after 3 * 24 hours
end

:first, :first_at and :first_in all accept a point in time or a duration (number or time string). Use the symbol you think makes your schedule more readable.

Note: it's OK to change the first_at (a Time instance) directly:

job.first_at = Time.now + 10
job.first_at = Rufus::Scheduler.parse('2029-12-12')

The first argument (in all its flavours) accepts a :now or :immediately value. That schedules the first occurrence for immediate triggering. Consider:

require 'rufus-scheduler'

s = Rufus::Scheduler.new

n = Time.now; p [ :scheduled_at, n, n.to_f ]

s.every '3s', first: :now do
  n = Time.now; p [ :in, n, n.to_f ]
end

s.join

that'll output something like:

[:scheduled_at, 2014-01-22 22:21:21 +0900, 1390396881.344438]
[:in, 2014-01-22 22:21:21 +0900, 1390396881.6453865]
[:in, 2014-01-22 22:21:24 +0900, 1390396884.648807]
[:in, 2014-01-22 22:21:27 +0900, 1390396887.651686]
[:in, 2014-01-22 22:21:30 +0900, 1390396890.6571937]
...

:first_at_no_error

In some heavy-duty configurations, the :first_at setting might be set on a point of time before the actual scheduling/triggering occurs and will result in an error "cannot set first[_at|_in] in the past...". To prevent that, the :first_at_no_error option may be set to true.

scheduler.every '10h', first_at: Time.now + 10, first_at_no_error: true do
  # ...
end

As introduced in gh-342.

:last_at, :last_in, :last

This option is for repeat jobs (cron / every) only.

It indicates the point in time after which the job should unschedule itself.

scheduler.cron '5 23 * * *', last_in: '10d' do
  # ... do something every evening at 23:05 for 10 days
end

scheduler.every '10m', last_at: Time.now + 10 * 3600 do
  # ... do something every 10 minutes for 10 hours
end

scheduler.every '10m', last_in: 10 * 3600 do
  # ... do something every 10 minutes for 10 hours
end

:last, :last_at and :last_in all accept a point in time or a duration (number or time string). Use the symbol you think makes your schedule more readable.

Note: it's OK to change the last_at (nil or a Time instance) directly:

job.last_at = nil
  # remove the "last" bound

job.last_at = Rufus::Scheduler.parse('2029-12-12')
  # set the last bound

times: nb of times (before auto-unscheduling)

One can tell how many times a repeat job (CronJob or EveryJob) is to execute before unscheduling by itself.

scheduler.every '2d', times: 10 do
  # ... do something every two days, but not more than 10 times
end

scheduler.cron '0 23 * * *', times: 31 do
  # ... do something every day at 23:00 but do it no more than 31 times
end

It's OK to assign nil to :times to make sure the repeat job is not limited. It's useful when the :times is determined at scheduling time.

scheduler.cron '0 23 * * *', times: (nolimit ? nil : 10) do
  # ...
end

The value set by :times is accessible in the job. It can be modified anytime.

job =
  scheduler.cron '0 23 * * *' do
    # ...
  end

# later on...

job.times = 10
  # 10 days and it will be over

discard_past: false/true/:fail

in and at accept a discard_past: option since rufus-scheduler 3.9.0:

require 'rufus-scheduler'

scheduler = Rufus::Scheduler.new

scheduler.in(-3600, discard_past: true) {}
  # the job will never get scheduled

scheduler.in(-3600, discard_past: false) {}
  # the job will trigger immediately

scheduler.in(-3600, discard_past: :fail) {}
  # will raise an error...

Please note that discard_past can be set at the scheduler level:

require 'rufus-scheduler'

s0 = Rufus::Scheduler.new(discard_past: true) # default

s1 = Rufus::Scheduler.new(discard_past: false)
  # or
s1 = Rufus::Scheduler.new
s1.discard_past = false

s2 = Rufus::Scheduler.new(discard_past: :fail)
  # or
s2 = Rufus::Scheduler.new
s2.discard_past = :fail

Job methods

When calling a schedule method, the id (String) of the job is returned. Longer schedule methods return Job instances directly. Calling the shorter schedule methods with the job: true also returns Job instances instead of Job ids (Strings).

  require 'rufus-scheduler'

  scheduler = Rufus::Scheduler.new

  job_id =
    scheduler.in '10d' do
      # ...
    end

  job =
    scheduler.schedule_in '1w' do
      # ...
    end

  job =
    scheduler.in '1w', job: true do
      # ...
    end

Those Job instances have a few interesting methods / properties:

id, job_id

Returns the job id.

job = scheduler.schedule_in('10d') do; end
job.id
  # => "in_1374072446.8923042_0.0_0"

scheduler

Returns the scheduler instance itself.

opts

Returns the options passed at the Job creation.

job = scheduler.schedule_in('10d', tag: 'hello') do; end
job.opts
  # => { :tag => 'hello' }

original

Returns the original schedule.

job = scheduler.schedule_in('10d', tag: 'hello') do; end
job.original
  # => '10d'

callable, handler

callable() returns the scheduled block (or the call method of the callable object passed in lieu of a block)

handler() returns nil if a block was scheduled and the instance scheduled otherwise.

# when passing a block

job =
  scheduler.schedule_in('10d') do
    # ...
  end

job.handler
  # => nil
job.callable
  # => #<Proc:0x00000001dc6f58@/home/jmettraux/whatever.rb:115>

and

# when passing something else than a block

class MyHandler
  attr_reader :counter
  def initialize
    @counter = 0
  end
  def call(job, time)
    @counter = @counter + 1
  end
end

job = scheduler.schedule_in('10d', MyHandler.new)

job.handler
  # => #<Method: MyHandler#call>
job.callable
  # => #<MyHandler:0x0000000163ae88 @counter=0>

source_location

Added to rufus-scheduler 3.8.0.

Returns the array [ 'path/to/file.rb', 123 ] like Proc#source_location does.

require 'rufus-scheduler'

scheduler = Rufus::Scheduler.new

job = scheduler.schedule_every('2h') { p Time.now }

p job.source_location
  # ==> [ '/home/jmettraux/rufus-scheduler/test.rb', 6 ]

scheduled_at

Returns the Time instance when the job got created.

job = scheduler.schedule_in('10d', tag: 'hello') do; end
job.scheduled_at
  # => 2013-07-17 23:48:54 +0900

last_time

Returns the last time the job triggered (is usually nil for AtJob and InJob).

job = scheduler.schedule_every('10s') do; end

job.scheduled_at
  # => 2013-07-17 23:48:54 +0900
job.last_time
  # => nil (since we've just scheduled it)

# after 10 seconds

job.scheduled_at
  # => 2013-07-17 23:48:54 +0900 (same as above)
job.last_time
  # => 2013-07-17 23:49:04 +0900

previous_time

Returns the previous #next_time

scheduler.every('10s') do |job|
  puts "job scheduled for #{job.previous_time} triggered at #{Time.now}"
  puts "next time will be around #{job.next_time}"
  puts "."
end

last_work_time, mean_work_time

The job keeps track of how long its work was in the last_work_time attribute. For a one time job (in, at) it's probably not very useful.

The attribute mean_work_time contains a computed mean work time. It's recomputed after every run (if it's a repeat job).

next_times(n)

Returns an array of EtOrbi::EoTime instances (Time instances with a designated time zone), listing the n next occurrences for this job.

Please note that for "interval" jobs, a mean work time is computed each time and it's used by this #next_times(n) method to approximate the next times beyond the immediate next time.

unschedule

Unschedule the job, preventing it from firing again and removing it from the schedule. This doesn't prevent a running thread for this job to run until its end.

threads

Returns the list of threads currently "hosting" runs of this Job instance.

kill

Interrupts all the work threads currently running for this job instance. They discard their work and are free for their next run (of whatever job).

Note: this doesn't unschedule the Job instance.

Note: if the job is pooled for another run, a free work thread will probably pick up that next run and the job will appear as running again. You'd have to unschedule and kill to make sure the job doesn't run again.

running?

Returns true if there is at least one running Thread hosting a run of this Job instance.

scheduled?

Returns true if the job is scheduled (is due to trigger). For repeat jobs it should return true until the job gets unscheduled. "at" and "in" jobs will respond with false as soon as they start running (execution triggered).

pause, resume, paused?, paused_at

These four methods are only available to CronJob, EveryJob and IntervalJob instances. One can pause or resume such jobs thanks to these methods.

job =
  scheduler.schedule_every('10s') do
    # ...
  end

job.pause
  # => 2013-07-20 01:22:22 +0900
job.paused?
  # => true
job.paused_at
  # => 2013-07-20 01:22:22 +0900

job.resume
  # => nil

tags

Returns the list of tags attached to this Job instance.

By default, returns an empty array.

job = scheduler.schedule_in('10d') do; end
job.tags
  # => []

job = scheduler.schedule_in('10d', tag: 'hello') do; end
job.tags
  # => [ 'hello' ]

[]=, [], key?, has_key?, keys, values, and entries

Threads have thread-local variables, similarly Rufus-scheduler jobs have job-local variables. Those are more like a dict with thread-safe access.

job =
  @scheduler.schedule_every '1s' do |job|
    job[:timestamp] = Time.now.to_f
    job[:counter] ||= 0
    job[:counter] += 1
  end

sleep 3.6

job[:counter]
  # => 3

job.key?(:timestamp) # => true
job.has_key?(:timestamp) # => true
job.keys # => [ :timestamp, :counter ]

Locals can be set at schedule time:

job0 =
  @scheduler.schedule_cron '*/15 12 * * *', locals: { a: 0 } do
    # ...
  end
job1 =
  @scheduler.schedule_cron '*/15 13 * * *', l: { a: 1 } do
    # ...
  end

One can fetch the Hash directly with Job#locals. Of course, direct manipulation is not thread-safe.

job.locals.entries do |k, v|
  p "#{k}: #{v}"
end

call

Job instances have a #call method. It simply calls the scheduled block or callable immediately.

job =
  @scheduler.schedule_every '10m' do |job|
    # ...
  end

job.call

Warning: the Scheduler#on_error handler is not involved. Error handling is the responsibility of the caller.

If the call has to be rescued by the error handler of the scheduler, call(true) might help:

require 'rufus-scheduler'

s = Rufus::Scheduler.new

def s.on_error(job, err)
  if job
    p [ 'error in scheduled job', job.class, job.original, err.message ]
  else
    p [ 'error while scheduling', err.message ]
  end
rescue
  p $!
end

job =
  s.schedule_in('1d') do
    fail 'again'
  end

job.call(true)
  #
  # true lets the error_handler deal with error in the job call

AtJob and InJob methods

time

Returns when the job will trigger (hopefully).

next_time

An alias for time.

EveryJob, IntervalJob and CronJob methods

next_time

Returns the next time the job will trigger (hopefully).

count

Returns how many times the job fired.

EveryJob methods

frequency

It returns the scheduling frequency. For a job scheduled "every 20s", it's 20.

It's used to determine if the job frequency is higher than the scheduler frequency (it raises an ArgumentError if that is the case).

IntervalJob methods

interval

Returns the interval scheduled between each execution of the job.

Every jobs use a time duration between each start of their execution, while interval jobs use a time duration between the end of an execution and the start of the next.

CronJob methods

brute_frequency

An expensive method to run, it's brute. It caches its results. By default it runs for 2017 (a non leap-year).

  require 'rufus-scheduler'

  Rufus::Scheduler.parse('* * * * *').brute_frequency
    #
    # => #<Fugit::Cron::Frequency:0x00007fdf4520c5e8
    #      @span=31536000.0, @delta_min=60, @delta_max=60,
    #      @occurrences=525600, @span_years=1.0, @yearly_occurrences=525600.0>
      #
      # Occurs 525600 times in a span of 1 year (2017) and 1 day.
      # There are least 60 seconds between "triggers" and at most 60 seconds.

  Rufus::Scheduler.parse('0 12 * * *').brute_frequency
    # => #<Fugit::Cron::Frequency:0x00007fdf451ec6d0
    #      @span=31536000.0, @delta_min=86400, @delta_max=86400,
    #      @occurrences=365, @span_years=1.0, @yearly_occurrences=365.0>
  Rufus::Scheduler.parse('0 12 * * *').brute_frequency.to_debug_s
    # => "dmin: 1D, dmax: 1D, ocs: 365, spn: 52W1D, spnys: 1, yocs: 365"
      #
      # 365 occurrences, at most 1 day between each, at least 1 day.

The CronJob#frequency method found in rufus-scheduler < 3.5 has been retired.

looking up jobs

Scheduler#job(job_id)

The scheduler #job(job_id) method can be used to look up Job instances.

  require 'rufus-scheduler'

  scheduler = Rufus::Scheduler.new

  job_id =
    scheduler.in '10d' do
      # ...
    end

  # later on...

  job = scheduler.job(job_id)

Scheduler #jobs #at_jobs #in_jobs #every_jobs #interval_jobs and #cron_jobs

Are methods for looking up lists of scheduled Job instances.

Here is an example:

  #
  # let's unschedule all the at jobs

  scheduler.at_jobs.each(&:unschedule)

Scheduler#jobs(tag: / tags: x)

When scheduling a job, one can specify one or more tags attached to the job. These can be used to look up the job later on.

  scheduler.in '10d', tag: 'main_process' do
    # ...
  end
  scheduler.in '10d', tags: [ 'main_process', 'side_dish' ] do
    # ...
  end

  # ...

  jobs = scheduler.jobs(tag: 'main_process')
    # find all the jobs with the 'main_process' tag

  jobs = scheduler.jobs(tags: [ 'main_process', 'side_dish' ]
    # find all the jobs with the 'main_process' AND 'side_dish' tags

Scheduler#running_jobs

Returns the list of Job instance that have currently running instances.

Whereas other "_jobs" method scan the scheduled job list, this method scans the thread list to find the job. It thus comprises jobs that are running but are not scheduled anymore (that happens for at and in jobs).

misc Scheduler methods

Scheduler#unschedule(job_or_job_id)

Unschedule a job given directly or by its id.

Scheduler#shutdown

Shuts down the scheduler, ceases any scheduler/triggering activity.

Scheduler#shutdown(:wait)

Shuts down the scheduler, waits (blocks) until all the jobs cease running.

Scheduler#shutdown(wait: n)

Shuts down the scheduler, waits (blocks) at most n seconds until all the jobs cease running. (Jobs are killed after n seconds have elapsed).

Scheduler#shutdown(:kill)

Kills all the job (threads) and then shuts the scheduler down. Radical.

Scheduler#down?

Returns true if the scheduler has been shut down.

Scheduler#started_at

Returns the Time instance at which the scheduler got started.

Scheduler #uptime / #uptime_s

Returns since the count of seconds for which the scheduler has been running.

#uptime_s returns this count in a String easier to grasp for humans, like "3d12m45s123".

Scheduler#join

Lets the current thread join the scheduling thread in rufus-scheduler. The thread comes back when the scheduler gets shut down.

#join is mostly used in standalone scheduling script (or tiny one file examples). Calling #join from a web application initializer will probably hijack the main thread and prevent the web application from being served. Do not put a #join in such a web application initializer file.

Scheduler#threads

Returns all the threads associated with the scheduler, including the scheduler thread itself.

Scheduler#work_threads(query=:all/:active/:vacant)

Lists the work threads associated with the scheduler. The query option defaults to :all.

  • :all : all the work threads
  • :active : all the work threads currently running a Job
  • :vacant : all the work threads currently not running a Job

Note that the main schedule thread will be returned if it is currently running a Job (ie one of those blocking: true jobs).

Scheduler#scheduled?(job_or_job_id)

Returns true if the arg is a currently scheduled job (see Job#scheduled?).

Scheduler#occurrences(time0, time1)

Returns a hash { job => [ t0, t1, ... ] } mapping jobs to their potential trigger time within the [ time0, time1 ] span.

Please note that, for interval jobs, the #mean_work_time is used, so the result is only a prediction.

Scheduler#timeline(time0, time1)

Like #occurrences but returns a list [ [ t0, job0 ], [ t1, job1 ], ... ] of time + job pairs.

dealing with job errors

The easy, job-granular way of dealing with errors is to rescue and deal with them immediately. The two next sections show examples. Skip them for explanations on how to deal with errors at the scheduler level.

block jobs

As said, jobs could take care of their errors themselves.

scheduler.every '10m' do
  begin
    # do something that might fail...
  rescue => e
    $stderr.puts '-' * 80
    $stderr.puts e.message
    $stderr.puts e.stacktrace
    $stderr.puts '-' * 80
  end
end

callable jobs

Jobs are not only shrunk to blocks, here is how the above would look like with a dedicated class.

scheduler.every '10m', Class.new do
  def call(job)
    # do something that might fail...
  rescue => e
    $stderr.puts '-' * 80
    $stderr.puts e.message
    $stderr.puts e.stacktrace
    $stderr.puts '-' * 80
  end
end

TODO: talk about callable#on_error (if implemented)

(see scheduling handler instances and scheduling handler classes for more about those "callable jobs")

Rufus::Scheduler#stderr=

By default, rufus-scheduler intercepts all errors (that inherit from StandardError) and dumps abundant details to $stderr.

If, for example, you'd like to divert that flow to another file (descriptor), you can reassign $stderr for the current Ruby process

$stderr = File.open('/var/log/myapplication.log', 'ab')

or, you can limit that reassignement to the scheduler itself

scheduler.stderr = File.open('/var/log/myapplication.log', 'ab')

Rufus::Scheduler#on_error(job, error)

We've just seen that, by default, rufus-scheduler dumps error information to $stderr. If one needs to completely change what happens in case of error, it's OK to overwrite #on_error

def scheduler.on_error(job, error)

  Logger.warn("intercepted error in #{job.id}: #{error.message}")
end

On Rails, the on_error method redefinition might look like:

def scheduler.on_error(job, error)

  Rails.logger.error(
    "err#{error.object_id} rufus-scheduler intercepted #{error.inspect}" +
    " in job #{job.inspect}")
  error.backtrace.each_with_index do |line, i|
    Rails.logger.error(
      "err#{error.object_id} #{i}: #{line}")
  end
end

Callbacks

Rufus::Scheduler #on_pre_trigger and #on_post_trigger callbacks

One can bind callbacks before and after jobs trigger:

s = Rufus::Scheduler.new

def s.on_pre_trigger(job, trigger_time)
  puts "triggering job #{job.id}..."
end

def s.on_post_trigger(job, trigger_time)
  puts "triggered job #{job.id}."
end

s.every '1s' do
  # ...
end

The trigger_time is the time at which the job triggers. It might be a bit before Time.now.

Warning: these two callbacks are executed in the scheduler thread, not in the work threads (the threads where the job execution really happens).

Rufus::Scheduler#around_trigger

One can create an around callback which will wrap a job:

def s.around_trigger(job)
  t = Time.now
  puts "Starting job #{job.id}..."
  yield
  puts "job #{job.id} finished in #{Time.now-t} seconds."
end

The around callback is executed in the thread.

Rufus::Scheduler#on_pre_trigger as a guard

Returning false in on_pre_trigger will prevent the job from triggering. Returning anything else (nil, -1, true, ...) will let the job trigger.

Note: your business logic should go in the scheduled block itself (or the scheduled instance). Don't put business logic in on_pre_trigger. Return false for admin reasons (backend down, etc), not for business reasons that are tied to the job itself.

def s.on_pre_trigger(job, trigger_time)

  return false if Backend.down?

  puts "triggering job #{job.id}..."
end

Rufus::Scheduler.new options

:frequency

By default, rufus-scheduler sleeps 0.300 second between every step. At each step it checks for jobs to trigger and so on.

The :frequency option lets you change that 0.300 second to something else.

scheduler = Rufus::Scheduler.new(frequency: 5)

It's OK to use a time string to specify the frequency.

scheduler = Rufus::Scheduler.new(frequency: '2h10m')
  # this scheduler will sleep 2 hours and 10 minutes between every "step"

Use with care.

lockfile: "mylockfile.txt"

This feature only works on OSes that support the flock (man 2 flock) call.

Starting the scheduler with lockfile: '.rufus-scheduler.lock' will make the scheduler attempt to create and lock the file .rufus-scheduler.lock in the current working directory. If that fails, the scheduler will not start.

The idea is to guarantee only one scheduler (in a group of schedulers sharing the same lockfile) is running.

This is useful in environments where the Ruby process holding the scheduler gets started multiple times.

If the lockfile mechanism here is not sufficient, you can plug your custom mechanism. It's explained in advanced lock schemes below.

:scheduler_lock

(since rufus-scheduler 3.0.9)

The scheduler lock is an object that responds to #lock and #unlock. The scheduler calls #lock when starting up. If the answer is false, the scheduler stops its initialization work and won't schedule anything.

Here is a sample of a scheduler lock that only lets the scheduler on host "coffee.example.com" start:

class HostLock
  def initialize(lock_name)
    @lock_name = lock_name
  end
  def lock
    @lock_name == `hostname -f`.strip
  end
  def unlock
    true
  end
end

scheduler =
  Rufus::Scheduler.new(scheduler_lock: HostLock.new('coffee.example.com'))

By default, the scheduler_lock is an instance of Rufus::Scheduler::NullLock, with a #lock that returns true.

:trigger_lock

(since rufus-scheduler 3.0.9)

The trigger lock in an object that responds to #lock. The scheduler calls that method on the job lock right before triggering any job. If the answer is false, the trigger doesn't happen, the job is not done (at least not in this scheduler).

Here is a (stupid) PingLock example, it'll only trigger if an "other host" is not responding to ping. Do not use that in production, you don't want to fork a ping process for each trigger attempt...

class PingLock
  def initialize(other_host)
    @other_host = other_host
  end
  def lock
    ! system("ping -c 1 #{@other_host}")
  end
end

scheduler =
  Rufus::Scheduler.new(trigger_lock: PingLock.new('main.example.com'))

By default, the trigger_lock is an instance of Rufus::Scheduler::NullLock, with a #lock that always returns true.

As explained in advanced lock schemes, another way to tune that behaviour is by overriding the scheduler's #confirm_lock method. (You could also do that with an #on_pre_trigger callback).

:max_work_threads

In rufus-scheduler 2.x, by default, each job triggering received its own, brand new, thread of execution. In rufus-scheduler 3.x, execution happens in a pooled work thread. The max work thread count (the pool size) defaults to 28.

One can set this maximum value when starting the scheduler.

scheduler = Rufus::Scheduler.new(max_work_threads: 77)

It's OK to increase the :max_work_threads of a running scheduler.

scheduler.max_work_threads += 10

Rufus::Scheduler.singleton

Do not want to store a reference to your rufus-scheduler instance? Then Rufus::Scheduler.singleton can help, it returns a singleton instance of the scheduler, initialized the first time this class method is called.

Rufus::Scheduler.singleton.every '10s' { puts "hello, world!" }

It's OK to pass initialization arguments (like :frequency or :max_work_threads) but they will only be taken into account the first time .singleton is called.

Rufus::Scheduler.singleton(max_work_threads: 77)
Rufus::Scheduler.singleton(max_work_threads: 277) # no effect

The .s is a shortcut for .singleton.

Rufus::Scheduler.s.every '10s' { puts "hello, world!" }

advanced lock schemes

As seen above, rufus-scheduler proposes the :lockfile system out of the box. If in a group of schedulers only one is supposed to run, the lockfile mechanism prevents schedulers that have not set/created the lockfile from running.

There are situations where this is not sufficient.

By overriding #lock and #unlock, one can customize how schedulers lock.

This example was provided by Eric Lindvall:

class ZookeptScheduler < Rufus::Scheduler

  def initialize(zookeeper, opts={})
    @zk = zookeeper
    super(opts)
  end

  def lock
    @zk_locker = @zk.exclusive_locker('scheduler')
    @zk_locker.lock # returns true if the lock was acquired, false else
  end

  def unlock
    @zk_locker.unlock
  end

  def confirm_lock
    return false if down?
    @zk_locker.assert!
  rescue ZK::Exceptions::LockAssertionFailedError => e
    # we've lost the lock, shutdown (and return false to at least prevent
    # this job from triggering
    shutdown
    false
  end
end

This uses a zookeeper to make sure only one scheduler in a group of distributed schedulers runs.

The methods #lock and #unlock are overridden and #confirm_lock is provided, to make sure that the lock is still valid.

The #confirm_lock method is called right before a job triggers (if it is provided). The more generic callback #on_pre_trigger is called right after #confirm_lock.

:scheduler_lock and :trigger_lock

(introduced in rufus-scheduler 3.0.9).

Another way of prodiving #lock, #unlock and #confirm_lock to a rufus-scheduler is by using the :scheduler_lock and :trigger_lock options.

See :trigger_lock and :scheduler_lock.

The scheduler lock may be used to prevent a scheduler from starting, while a trigger lock prevents individual jobs from triggering (the scheduler goes on scheduling).

One has to be careful with what goes in #confirm_lock or in a trigger lock, as it gets called before each trigger.

Warning: you may think you're heading towards "high availability" by using a trigger lock and having lots of schedulers at hand. It may be so if you limit yourself to scheduling the same set of jobs at scheduler startup. But if you add schedules at runtime, they stay local to their scheduler. There is no magic that propagates the jobs to all the schedulers in your pack.

parsing cronlines and time strings

(Please note that fugit does the heavy-lifting parsing work for rufus-scheduler).

Rufus::Scheduler provides a class method .parse to parse time durations and cron strings. It's what it's using when receiving schedules. One can use it directly (no need to instantiate a Scheduler).

require 'rufus-scheduler'

Rufus::Scheduler.parse('1w2d')
  # => 777600.0
Rufus::Scheduler.parse('1.0w1.0d')
  # => 777600.0

Rufus::Scheduler.parse('Sun Nov 18 16:01:00 2012').strftime('%c')
  # => 'Sun Nov 18 16:01:00 2012'

Rufus::Scheduler.parse('Sun Nov 18 16:01:00 2012 Europe/Berlin').strftime('%c %z')
  # => 'Sun Nov 18 15:01:00 2012 +0000'

Rufus::Scheduler.parse(0.1)
  # => 0.1

Rufus::Scheduler.parse('* * * * *')
  # => #<Fugit::Cron:0x00007fb7a3045508
  #      @original="* * * * *", @cron_s=nil,
  #      @seconds=[0], @minutes=nil, @hours=nil, @monthdays=nil, @months=nil,
  #      @weekdays=nil, @zone=nil, @timezone=nil>

It returns a number when the input is a duration and a Fugit::Cron instance when the input is a cron string.

It will raise an ArgumentError if it can't parse the input.

Beyond .parse, there are also .parse_cron and .parse_duration, for finer granularity.

There is an interesting helper method named .to_duration_hash:

require 'rufus-scheduler'

Rufus::Scheduler.to_duration_hash(60)
  # => { :m => 1 }
Rufus::Scheduler.to_duration_hash(62.127)
  # => { :m => 1, :s => 2, :ms => 127 }

Rufus::Scheduler.to_duration_hash(62.127, drop_seconds: true)
  # => { :m => 1 }

cronline notations specific to rufus-scheduler

first Monday, last Sunday et al

To schedule something at noon every first Monday of the month:

scheduler.cron('00 12 * * mon#1') do
  # ...
end

To schedule something at noon the last Sunday of every month:

scheduler.cron('00 12 * * sun#-1') do
  # ...
end
#
# OR
#
scheduler.cron('00 12 * * sun#L') do
  # ...
end

Such cronlines can be tested with scripts like:

require 'rufus-scheduler'

Time.now
  # => 2013-10-26 07:07:08 +0900
Rufus::Scheduler.parse('* * * * mon#1').next_time.to_s
  # => 2013-11-04 00:00:00 +0900

L (last day of month)

L can be used in the "day" slot:

In this example, the cronline is supposed to trigger every last day of the month at noon:

require 'rufus-scheduler'
Time.now
  # => 2013-10-26 07:22:09 +0900
Rufus::Scheduler.parse('00 12 L * *').next_time.to_s
  # => 2013-10-31 12:00:00 +0900

negative day (x days before the end of the month)

It's OK to pass negative values in the "day" slot:

scheduler.cron '0 0 -5 * *' do
  # do it at 00h00 5 days before the end of the month...
end

Negative ranges (-10--5-: 10 days before the end of the month to 5 days before the end of the month) are OK, but mixed positive / negative ranges will raise an ArgumentError.

Negative ranges with increments (-10---2/2) are accepted as well.

Descending day ranges are not accepted (10-8 or -8--10 for example).

a note about timezones

Cron schedules and at schedules support the specification of a timezone.

scheduler.cron '0 22 * * 1-5 America/Chicago' do
  # the job...
end

scheduler.at '2013-12-12 14:00 Pacific/Samoa' do
  puts "it's tea time!"
end

# or even

Rufus::Scheduler.parse("2013-12-12 14:00 Pacific/Saipan")
  # => #<Rufus::Scheduler::ZoTime:0x007fb424abf4e8 @seconds=1386820800.0, @zone=#<TZInfo::DataTimezone: Pacific/Saipan>, @time=nil>

I get "zotime.rb:41:in `initialize': cannot determine timezone from nil"

For when you see an error like:

rufus-scheduler/lib/rufus/scheduler/zotime.rb:41:
  in `initialize':
    cannot determine timezone from nil (etz:nil,tnz:"**ๆ ‡ๅ‡†ๆ—ถ้—ด",tzid:nil)
      (ArgumentError)
	from rufus-scheduler/lib/rufus/scheduler/zotime.rb:198:in `new'
	from rufus-scheduler/lib/rufus/scheduler/zotime.rb:198:in `now'
	from rufus-scheduler/lib/rufus/scheduler.rb:561:in `start'
	...

It may happen on Windows or on systems that poorly hint to Ruby which timezone to use. It should be solved by setting explicitly the ENV['TZ'] before the scheduler instantiation:

ENV['TZ'] = 'Asia/Shanghai'
scheduler = Rufus::Scheduler.new
scheduler.every '2s' do
  puts "#{Time.now} Hello #{ENV['TZ']}!"
end

On Rails you might want to try with:

ENV['TZ'] = Time.zone.name # Rails only
scheduler = Rufus::Scheduler.new
scheduler.every '2s' do
  puts "#{Time.now} Hello #{ENV['TZ']}!"
end

(Hat tip to Alexander in gh-230)

Rails sets its timezone under config/application.rb.

Rufus-Scheduler 3.3.3 detects the presence of Rails and uses its timezone setting (tested with Rails 4), so setting ENV['TZ'] should not be necessary.

The value can be determined thanks to https://en.wikipedia.org/wiki/List_of_tz_database_time_zones.

Use a "continent/city" identifier (for example "Asia/Shanghai"). Do not use an abbreviation (not "CST") and do not use a local time zone name (not "**ๆ ‡ๅ‡†ๆ—ถ้—ด" nor "Eastern Standard Time" which, for instance, points to a time zone in America and to another one in Australia...).

If the error persists (and especially on Windows), try to add the tzinfo-data to your Gemfile, as in:

gem 'tzinfo-data'

or by manually requiring it before requiring rufus-scheduler (if you don't use Bundler):

require 'tzinfo/data'
require 'rufus-scheduler'

Timezone in the schedule thread

Currently (3.9.x), rufus-scheduler strives to trigger at the right time. The trigger thread might not yield a Time.now in the scheduled timezone.

ENV['TZ'] = 'Asia/Tokyo'

require 'rufus-scheduler'

s = Rufus::Scheduler.new

s.cron('*/5 * * * * * Europe/Rome') do
  p Time.now # ==> the representation will indicate the time is UTC+0900...
end

s.join

In the wake of gh-341.

so Rails?

Yes, I know, all of the above is boring and you're only looking for a snippet to paste in your Ruby-on-Rails application to schedule...

Here is an example initializer:

#
# config/initializers/scheduler.rb

require 'rufus-scheduler'

# Let's use the rufus-scheduler singleton
#
s = Rufus::Scheduler.singleton


# Stupid recurrent task...
#
s.every '1m' do

  Rails.logger.info "hello, it's #{Time.now}"
  Rails.logger.flush
end

And now you tell me that this is good, but you want to schedule stuff from your controller.

Maybe:

class ScheController < ApplicationController

  # GET /sche/
  #
  def index

    job_id =
      Rufus::Scheduler.singleton.in '5s' do
        Rails.logger.info "time flies, it's now #{Time.now}"
      end

    render text: "scheduled job #{job_id}"
  end
end

The rufus-scheduler singleton is instantiated in the config/initializers/scheduler.rb file, it's then available throughout the webapp via Rufus::Scheduler.singleton.

Warning: this works well with single-process Ruby servers like Webrick and Thin. Using rufus-scheduler with Passenger or Unicorn requires a bit more knowledge and tuning, gently provided by a bit of googling and reading, see Faq above.

avoid scheduling when running the Ruby on Rails console

(Written in reply to gh-186)

If you don't want rufus-scheduler to trigger anything while running the Ruby on Rails console, running for tests/specs, or running from a Rake task, you can insert a conditional return statement before jobs are added to the scheduler instance:

#
# config/initializers/scheduler.rb

require 'rufus-scheduler'

return if defined?(Rails::Console) || Rails.env.test? || File.split($PROGRAM_NAME).last == 'rake'
  #
  # do not schedule when Rails is run from its console, for a test/spec, or
  # from a Rake task

# return if $PROGRAM_NAME.include?('spring')
  #
  # see https://github.com/jmettraux/rufus-scheduler/issues/186

s = Rufus::Scheduler.singleton

s.every '1m' do
  Rails.logger.info "hello, it's #{Time.now}"
  Rails.logger.flush
end

(Beware later version of Rails where Spring takes care pre-running the initializers. Running spring stop or disabling Spring might be necessary in some cases to see changes to initializers being taken into account.)

rails server -d

(Written in reply to #165 )

There is the handy rails server -d that starts a development Rails as a daemon. The annoying thing is that the scheduler as seen above is started in the main process that then gets forked and daemonized. The rufus-scheduler thread (and any other thread) gets lost, no scheduling happens.

I avoid running -d in development mode and bother about daemonizing only for production deployment.

These are two well crafted articles on process daemonization, please read them:

If, anyway, you need something like rails server -d, why not try bundle exec unicorn -D instead? In my (limited) experience, it worked out of the box (well, had to add gem 'unicorn' to Gemfile first).

executor / reloader

You might benefit from wraping your scheduled code in the executor or reloader. Read more here: https://guides.rubyonrails.org/threading_and_code_execution.html

support

see getting help above.

license

MIT, see LICENSE.txt

rufus-scheduler's People

Contributors

accessd avatar achasveachas avatar adz avatar andrehjr avatar anjali-sharma avatar bf4 avatar chrisk avatar dependabot[bot] avatar dsander avatar ecin avatar ghostsquad avatar jjb avatar jmettraux avatar korrigan avatar lfu avatar mike-yesware avatar northox avatar olleolleolle avatar paulodelgado avatar pouellet avatar prayagverma avatar rainux avatar rmm5t avatar simook avatar solackerman avatar stigkj avatar tedpennings avatar vais avatar yaauie avatar yassenb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rufus-scheduler's Issues

ThreadError: can't create Thread

I get this error randomly about once a day while rufus is running. Any ideas what the cause could be or what we could do to diagnose it?

The error we see in our logs is here: vendor/bundle/ruby/1.9.1/gems/rufus-scheduler-2.0.17/lib/rufus/sc/scheduler.rb:416

Certain cron strings are not firing off reliably

I am having issues using cron strings to schedule tasks. Some work. while others are hit or miss.

One example:

*/10 8-21 * * 1,2,3,4,5,6,0

Todays runtimes, thus far:

2011-06-16 14:50:03.462913
2011-06-16 14:40:03.13553
2011-06-16 14:30:22.214137
2011-06-16 14:20:15.99141
2011-06-16 14:00:40.506319
2011-06-16 13:40:06.077922
2011-06-16 13:30:25.126185
2011-06-16 12:50:05.149763
2011-06-16 12:30:09.415943
2011-06-16 12:20:07.07834
2011-06-16 11:50:04.091377
2011-06-16 11:40:03.0094
2011-06-16 11:30:08.589346
2011-06-16 11:20:02.680793
2011-06-16 11:10:38.189631
2011-06-16 11:00:10.511167
2011-06-16 10:50:01.390877
2011-06-16 10:31:37.687301
2011-06-16 10:20:30.24467
2011-06-16 10:10:14.310773
2011-06-16 10:00:13.219968
2011-06-16 09:50:02.515267
2011-06-16 09:31:02.410128
2011-06-16 09:00:54.056624
2011-06-16 08:50:02.930265
2011-06-16 08:40:35.890845
2011-06-16 08:20:04.776577
2011-06-16 08:10:08.833181
2011-06-16 08:00:22.189841
2011-06-16 07:50:08.588737
2011-06-16 07:40:20.018557
2011-06-16 07:30:30.257125
2011-06-16 07:20:03.62041
2011-06-16 07:00:40.56041

As you can see, it just likes to randomly skip some. Am I doing something wrong or is this just a bug?

Cron lines don't work in production when minutes are "0"

Hey,

I know that the issue sounds a little but strange, but my cron jobs don't work, when I set minutes to "0".

I have a setup with a local Rails 3.0.12 app on OSX Lion in development environment and the online version, which is hosted on a VPS running Ubuntu 10.04.

My task_scheduler.rb has several job runnings, which are always similar to one of the following lines:

scheduler.in '1m' do
scheduler.every '1h' do
scheduler.cron '0 12 * * 1-7' do

The first line is for testing and always works in development as in production mode. The second line with 'every' also works in both environments. The problem I have is with the third line.

In my local development mode the cron task works and does what it should be. But on my production server it is not executed. But after playing around with the code, I found out, that the job gets executed when it's set to another time. So

scheduler.cron '15 12 * * 1-7' do

works just fine. After finding out it's not a problem anymore, but it still seems very odd, which is why I wanted to let you know. And yes, I tested it several times and tried several numbers and really the only line which does not work is when minutes is set to '0'.

Weird output when using :first_at

Hello John,

I have a weird problem while using rufus-scheduler within ruote.

The problem only appears when I'm using :first_at.

Both:

- scheduler.every '1m', :first_at => '2012/10/23 22:10:00' do |job|
- scheduler.every '1m', :first_at => DateTime.new(2012,10,23,13,22,30) do |job|

will create a weird output but:

- scheduler.every '1m', :first_in => '30s' do |job|
- scheduler.every '1m' do |job|

would be ok. See this gist. I'm I doing something wrong?

I'm using rufus-scheduler 2.0.17 and ruote master (2.3.1)

Scheduler just terminates randomly for no apparent reason

Strange problem: In my scenario Rufus Scheduler terminates at different points during task execution for no apparent reason.

This is my config/initializers/task_scheduler.rb:

require 'rufus/scheduler'

$scheduler = Rufus::Scheduler.start_new

$scheduler.every("5m") do
  custom_log("Keep-Alive Rufus log, time: #{Time.now}")
end

if %w!production staging!.include? Rails.env
  $scheduler.every("45m") do
    custom_log("autocomplete:generate, time: #{Time.now}")
    Rake::Task["autocomplete:generate"].invoke
  end

  $scheduler.every("30m") do
    custom_log("ts:index, time: #{Time.now}")
    Rake::Task["ts:index"].invoke
  end

  $scheduler.every('30m') do
    custom_log("Checking for new contact requests in Contact.unsent.inspect - time: #{Time.now}")
    Contact.unsent.each do |contact|
      Mailer.deliver_mimi_contact_request(contact)
      Mailer.deliver_mimi_contact_requested(contact)
      contact.update_attribute(:notification_sent, true)
    end
  end
end

Now, when I restart passenger I always get mixed results how "far" rufus gets before he terminates:

This is from today:

# Restart passenger
Keep-Alive Rufus log, time: Wed Dec 01 12:06:36 -0800 2010
Keep-Alive Rufus log, time: Wed Dec 01 12:11:36 -0800 2010
Keep-Alive Rufus log, time: Wed Dec 01 12:16:36 -0800 2010
Keep-Alive Rufus log, time: Wed Dec 01 12:21:36 -0800 2010
Keep-Alive Rufus log, time: Wed Dec 01 12:26:36 -0800 2010
Keep-Alive Rufus log, time: Wed Dec 01 12:31:36 -0800 2010
ts:index, time: Wed Dec 01 12:31:36 -0800 2010
Checking for new contact requests in Contact.unsent.inspect - time: Wed Dec 01 12:31:36 -0800 2010
Keep-Alive Rufus log, time: Wed Dec 01 12:36:36 -0800 2010
Keep-Alive Rufus log, time: Wed Dec 01 12:41:36 -0800 2010
Keep-Alive Rufus log, time: Wed Dec 01 12:46:35 -0800 2010
autocomplete:generate, time: Wed Dec 01 12:46:35 -0800 2010
# -> nothing more after here

2 days before:

# Restart passenger
Keep-Alive Rufus log, time: Mon Nov 29 01:26:32 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 01:31:31 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 01:36:31 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 01:41:31 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 01:46:31 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 01:51:31 -0800 2010
ts:index, time: Mon Nov 29 01:51:31 -0800 2010
Checking for new contact requests in Contact.unsent.inspect - time: Mon Nov 29 01:51:31 -0800 2010
# -> nothing more after here

From the same day:

# Restart passenger
Keep-Alive Rufus log, time: Mon Nov 29 15:39:19 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 15:44:20 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 15:49:19 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 15:54:20 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 15:59:19 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 16:04:20 -0800 2010
ts:index, time: Mon Nov 29 16:04:20 -0800 2010
Checking for new contact requests in Contact.unsent.inspect - time: Mon Nov 29 16:04:20 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 16:09:20 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 16:14:19 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 16:19:20 -0800 2010
autocomplete:generate, time: Mon Nov 29 16:19:20 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 16:24:19 -0800 2010
Keep-Alive Rufus log, time: Mon Nov 29 16:29:20 -0800 2010
# -> nothing more after here

As you can see, the scheduler just kind of stops working at seemingly random points. All of the jobs in my scheduler file run fine when executed by hand and, even worse, also fine by the scheduler because I can see in the logs that every job has been executed successfully multiple times.
I tried a lot of things:

  • Playing around with intervalls as I suspected some weird concurrency issue
  • Disabling / Enabling all possible mutations of running jobs

The result is always the frustrating one from - I can't see any system / logic behind Rufus just stopping to work.

How can I debug this further?

Sys-Info:

ruby -v
ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-linux]
gem -v
1.3.6
gem list rails
rails (2.3.5)

An exception whose #to_s or #backtrace method itself throws an exception stops the scheduler

But how do you commit such nefarious deeds, you might ask?

require 'rufus/scheduler'
class SnidelyWhiplash < Exception
  def to_s
    raise "*twirls mustachios*"
  end 

  def backtrace
    raise "MWAHAHAHAHAHAAHAHA.... *breath*.... MWAHAHAHAHAH"
  end
end

scheduler = Rufus::Scheduler.start_new
scheduler.every("1s", :blocking => true) { raise SnidelyWhiplash, "So eeeeeevil" }

What exactly is going on here?

In lib/rufus/sc/jobs.rb#147 there's a bit of code that rescues exceptions and calls #handle_exception.

        begin

          trigger_block

          job_thread = nil
          to_job.unschedule if to_job

        rescue Exception => e
          @scheduler.handle_exception(self, e) 

The default implementation of #handle_exception calls Exception#to_s and Exception#backtrace to print out the details of the error. If either of these methods raise an exception they bubble up all the way to the scheduler and seem to stop subsequent jobs from running (I'm not entirely clear why -- I think they actually go all the way up to the thread and the thread stops, but I'm not sure).

Either #handle_exception should be made (reasonably) safe from exceptions itself, or the scheduler should be resilient to any perfidious exceptions that manage to find their way up to the top. I'm not sure how to accomplish the second and I wasn't sure if the first was an approach that you would agree with, so instead of a patch I decided to submit a bug.

Trying to pass class as schedulable raises exception

Hi, digging rufus-scheduler - awesome gem! But I'm having problems with passing a schedulable. The docs say you can do this:

every '30s', GameProcessor.new

But trying to do that raises this exception:

undefined method merge' for GameProcessor:Class (NoMethodError) from /usr/playerconnect-stack-2009e/lib/ruby/gems/1.9.1/gems/rufus-scheduler-2.0.2/lib/rufus/sc/scheduler.rb:164:inevery'

It actually looks like the method to use was just renamed from call() to trigger(). If this is the case, can the README.rdoc be updated? Thanks again for the great gem!

cron jobs are unreliable with non-default scheduler frequency

I have a small script (using scheduler.join) that had a frequency of 10 seconds. My cron job would never run (every jobs work fine). Using the default frequency makes it work fine... maybe warn if users have changed the scheduler frequency when scheduling crons?

Does the code that determines what jobs to run only search back a set period of time (vs the frequency period?). Classic cron won't run jobs that weren't executed due to the machine sleeping when woken up... I guess Rufus is essentially asleep during the non-running periods.

Test code attached... you'll rarely see the cron line (basically when the frequency interval hits on the exact moment the cron job should fire).

Thanks,
Andy

////

TEST CODE:

require 'rufus/scheduler'

s = Rufus::Scheduler.start_new(:frequency => 13.0)

s.schedule("* * * * *") do
puts "#{Time.now}: cron"
end

s.every("1m") do
puts "#{Time.now}: 1m"
end

puts "#{Time.now}: start"
s.join

TEST OUTPUT:

dhcp-185:~/git/df/scripts (masterโšก) > ruby test.rb
2012-11-19 16:13:48 -0800: start
2012-11-19 16:14:53 -0800: 1m
2012-11-19 16:15:58 -0800: 1m
2012-11-19 16:16:50 -0800: 1m
2012-11-19 16:17:55 -0800: 1m
2012-11-19 16:19:00 -0800: 1m
2012-11-19 16:19:00 -0800: cron
2012-11-19 16:19:52 -0800: 1m
2012-11-19 16:20:57 -0800: 1m
2012-11-19 16:21:49 -0800: 1m
2012-11-19 16:22:54 -0800: 1m
2012-11-19 16:23:59 -0800: 1m
2012-11-19 16:24:51 -0800: 1m
2012-11-19 16:25:56 -0800: 1m
2012-11-19 16:26:48 -0800: 1m

Cron uses, and interactions.

Hello, Iยดm trying to code a scheduler with some "every" tasks and some of them to be executed exactly at a determined time, not depending on when the scheduler was started. So I used cron.

First of all, I donยดt know if I have to create the cron line before, or just using it directly. Here some code:
(itยดs a shortened version, but the important part, at least, what I think is there)

The version of Ruby is: 1.8.7 -p72
The version of Rufus Scheduler is: 2.0.5

[code]

repeat = Rufus::Scheduler::PlainScheduler.start_new

...

repeat.every #whenever do

whatever

end

...

repeat.cron '0 18 * * 1-5' do

whatever else

end

repeat.join

[code]

The thing is that I donยดt know for sure how the cron line is written and for what, the sintaxis of it, to be properly called. In any case it is not executing at that time. Neither in some days of uninterrupted work. As far as I know that cronstring will make it to be executed at 18:00 pm every day of the week, right?

Second to it, if it happened that a task that is already running, with " :blocking=>true ", and then the time of the cron task to be executed is reached, if it will start after the ongoing task is finished, or if it will skip.

The fact is that Iยดm having some trouble trying to fix a time for some tasks. I have tried changing the frequency to the default one, <1s, as seen in a previous post.

Before the obvious thing of updating the versions, need to be said, that the code is made in that version, years ago, and it is some how long enough to not be, in any way easy, checked for forward compatibility. Without messing it all up.

Thanks.

scheduler running for 10 minutes then stopping

Very odd problem ... I have a scheduler setup up to run every 30 minutes ... at first I noticed that it wasn't running, so I reduced the interval to 5 minutes then 1 minute ... and from my tests, it seems that it runs for about 10 minutes then stops

We're running this with Passenger 3.0.4 and Apache 2.2.11, rufus scheduler 2.0.9.

I'm very confused.

Event storm triggered after waking up from sleep-mode

When running programs powered by Rufus-Scheduler I do recognize the scheduler is triggering a storm of events after waking up from hybernation mode (or sleep mode). In this case all missed triggers are fired up as fast as possible.

I did not find a reliable mechanism to prevent this behaviour or to configure Rufus to forget events that are too old.

add #scheduled? to Job class

for "at" and "in" jobs, it's interesting to determine if it's still in the game...

although, if Time.now > job.at...

License missing from gemspec

Some companies will only use gems with a certain license.
The canonical and easy way to check is via the gemspec
via e.g.

spec.license = 'MIT'
# or
spec.licenses = ['MIT', 'GPL-2']

There is even a License Finder to help companies ensure all gems they use
meet their licensing needs. This tool depends on license information being available in the gemspec.
Including a license in your gemspec is a good practice, in any case.

How did I find you?

I'm using a script to collect stats on gems, originally looking for download data, but decided to collect licenses too,
and make issues for missing ones as a public service :)
https://gist.github.com/bf4/5952053#file-license_issue-rb-L13 So far it's going pretty well

Cannot stop a running job

Hello,
Thanks for a wonderful gem! I have a small problem with stopping a running job. Once the job disappears from:
scheduler.jobs
it goes to:
scheduler.running_jobs

i find the job by simply:
scheduler.running_jobs.select { |job| job.job_id == saved_in_database_job_id }
because, this doesn't work:
scheduler.find(saved_in_database_job_id)

The question is: how can i pause / resume / stop a job that is already running.
Example:
I'm sending 10000 emails in one loop to is run as a job scheduled in Rufus Scheduler. I noticed that i'm sending bad content and i want to stop it by using a button on my webpage. So, i'm retrieving the job by using:
@@scheduler.running_jobs.select { |job| job.job_id == saved_in_database_job_id }
What do i do next? How do i stop the running job?

Thank you for any advice! :-)

Rufus::Scheduler.start required in production

The following schedule begins executing immediately on my Mac in my development environment:

scheduler = Rufus::Scheduler.start_new
job = scheduler.every '1s' do
puts "hello world"
end

While on my Ubuntu 12.04 production box it requires a call to start() to begin executing:

scheduler = Rufus::Scheduler.start_new
job = scheduler.every '1s' do
puts "hello world"
end
scheduler.start

Both are Rails 3.2.3, ruby 1.9.3-p194, rufus-scheduler 2.0.16. I racked my brain on this one for a while before I finally tracked it down. Any luck reproducing?

RoR - many application servers

Hi,

I have been playing around with rufus-scheduler for a long time and I think it's really cool. I migrated my app today to be served with 4 thin servers using apache with mod_proxy as frontend server.

Having one instance of thin was easy because rufus was running as a thread of thin's process. What's the best approach to deal with 4 instances of thin and not having 4 instances of rufus?

Running it separately? Any suggestion?
Thanks,
Lukasz

Why I can't reschedule?

In Rails application, I want to reschedule the job:

class Scheduler
  def self.single
    @@single||= Rufus::Scheduler.start_new
  end

  def self.cron(time, tag)
    Scheduler.single.find_by_tag(tag).map(&:unschedule)
    Scheduler.single.cron time, tags: tag do |job|
      yield(job)
    end
  end
end

# schedule first
Scheduler.cron("0 02 * * *", "tag1") do |job|
   puts "Schedule...."
end

# reschedule 
Scheduler.cron("10 02 * * *", "tag1") do |job|
   puts "Schedule...."
end

I can't make the job to "10 02 * * *". Do you have any idea?

/cc @haobole

cron: support sun#L or sun#-1 (for last sunday)

19:58 furqan: i have a question, i have a scenario in which i have to send out email notifications every last tuesday and last friday of every month. can i accomplish this using rufus ?
19:58 jmettraux: yesยฅ
19:58 furqan: but how do i get last tuesday and friday ?
19:59 furqan: i know tue#1 is first tuesday, right ?
20:00 furqan: but how would i know which one is the last tuesday 4 or 5 ?
20:00 jmettraux: check if today + 7 days falls in the same month

That should be easy, and at least useful to one person.

Job initialization should complain about unknown/ineffective options

Job initialization happily accepts whatever options. If it did not, typos and false expectations of job capabilities would get caught earlier. Later is imo the more important issue. Now if you do scheduler.cron('15 * * * *', :first_at => Chronic.parse('this monday 00:15')) { work_my_magic } and it works ... except that it quite doesn't. :) It will fire every *:15 on every day, but it won't wait for for monday to start shooting because cron does not obey :first_in and :first_at.

Exception thrown from job stops execution of this job

In readme it's stated
'Note that an every job or a cron job will stay scheduled even if it experiences an exception.'
Seems ever readme is out of dated or in latest rufus-scheduler there is a bug regarding this, because exception actually stops scheduling faulty job.

Constantly uses 50% CPU on ruby 1.9.2p136 (2010-12-25) [i386-mingw32]

rufus-scheduler seems to constantly use 47 - 50% CPU running on ruby 1.9.2p136 (2010-12-25) [i386-mingw32]

require 'eventmachine'
require 'rufus-scheduler'

EM.run do
  scheduler = Rufus::Scheduler::EmScheduler.start_new
end

The above example works fine running under ruby 1.8.7

CronLine.next_time never completes for "0 17 * * MON_FRI"

We're using CronLine.new(expr) as a quick (maybe dirty) way to validate cron expressions entered by our users. For the expression "0 17 * * MON_FRI" the constructor returns a valid object, but calling next_time on it will block forever.

fix timeout issue on rubinius

as seen in https://travis-ci.org/jmettraux/rufus-scheduler/jobs/9454076

Failures:
  1) Rufus::Scheduler#cron schedules
     Failure/Error: Unable to find matching line from backtrace
     NoMethodError:
       undefined method `[]' on nil:NilClass.
     # kernel/delta/kernel.rb:81:in `[] (method_missing)'
     # ./lib/rufus/scheduler.rb:297:in `timeout_jobs'
     # kernel/bootstrap/array.rb:68:in `each'
     # ./lib/rufus/scheduler.rb:294:in `timeout_jobs'
     # ./lib/rufus/scheduler.rb:262:in `start'
     # kernel/bootstrap/proc.rb:22:in `call'
     # kernel/bootstrap/thread18.rb:54:in `__run__'
  2) Rufus::Scheduler::Job Rufus::Scheduler::RepeatJob #pause pauses the job
     Failure/Error: Unable to find matching line from backtrace
     NoMethodError:
       undefined method `[]' on nil:NilClass.
     # kernel/delta/kernel.rb:81:in `[] (method_missing)'
     # ./lib/rufus/scheduler.rb:297:in `timeout_jobs'
     # kernel/bootstrap/array.rb:68:in `each'
     # ./lib/rufus/scheduler.rb:294:in `timeout_jobs'
     # ./lib/rufus/scheduler.rb:262:in `start'
     # kernel/bootstrap/proc.rb:22:in `call'
     # kernel/bootstrap/thread18.rb:54:in `__run__'
  3) Rufus::Scheduler#unschedule(job_or_job_id) carefully unschedules repeat jobs
     Failure/Error: Unable to find matching line from backtrace
     NoMethodError:
       undefined method `[]' on nil:NilClass.
     # kernel/delta/kernel.rb:81:in `[] (method_missing)'
     # ./lib/rufus/scheduler.rb:297:in `timeout_jobs'
     # kernel/bootstrap/array.rb:68:in `each'
     # ./lib/rufus/scheduler.rb:294:in `timeout_jobs'
     # ./lib/rufus/scheduler.rb:262:in `start'
     # kernel/bootstrap/proc.rb:22:in `call'
     # kernel/bootstrap/thread18.rb:54:in `__run__'

midnight changing to 1 am

This spec test fails when I add it to cronline_spec.rb, line 53 (under "interpreting cron strings correctly")

to_a '0 0 1 1 *', [ [0], [0], [0], [0], [1], nil, nil ]

In my understanding this should run at midnight on January 1st, but instead it shifts to run at 1 a.m.

rufus scheduler implementation advice

I have a rufus scheduler implemented in an app where I schedule jobs from a db in an initializer. My understanding is how apache kicks off process, it will run the initializers multiple times which will cause duplicate jobs in rufus.

Is there a recommended way of initializing the scheduler and registering jobs?

scheduler.every '4h' problem

Hello,

[complex one here]

I have a Rails 3.0.5 app in production, that is running by Unicorn and MySQL, and from 4 to 4 hours it should run a model method. It actually does that, but in a strange way.. This method reads the db and based on what found create news proposals (via regular ActiveRecord).
The strange thing is, it seems to read a older version of the DB (but I use no particular cache), but does persist new data in a regular way.
Yet stranger, the web server can't read the new info that what was written for a large while OR until I restart the server.

unicorn config:

APP_PATH = '/web/soccerhero/'

# Use at least one worker per core if you're on a dedicated server,
# more will usually help for _short_ waits on databases/caches.
worker_processes 3

# Help ensure your application will always spawn in the symlinked
# "current" directory that Capistrano sets up.
working_directory APP_PATH # available in 0.94.0+

# listen on both a Unix domain socket and a TCP port,
# we use a shorter backlog for quicker failover when busy
listen "/tmp/soccerhero.sock", :backlog => 64
listen 8080, :tcp_nopush => true

# nuke workers after 30 seconds instead of 60 seconds (the default)
timeout 30

# feel free to point this anywhere accessible on the filesystem
pid APP_PATH+"tmp/pids/unicorn.pid"

# By default, the Unicorn logger will write to stderr.
# Additionally, ome applications/frameworks log to stderr or stdout,
# so prevent them from going to /dev/null when daemonized here:

stderr_path APP_PATH+"log/unicorn.stderr.log"
stdout_path APP_PATH+"log/unicorn.stdout.log"

# combine REE with "preload_app true" for memory savings
# http://rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
preload_app true
GC.respond_to?(:copy_on_write_friendly=) and
  GC.copy_on_write_friendly = true

before_fork do |server, worker|
  # the following is highly recomended for Rails + "preload_app true"
  # as there's no need for the master process to hold a connection
  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.connection.disconnect!

  # The following is only recommended for memory/DB-constrained
  # installations.  It is not needed if your system can house
  # twice as many worker_processes as you have configured.
  #
  # # This allows a new master process to incrementally
  # # phase out the old master process with SIGTTOU to avoid a
  # # thundering herd (especially in the "preload_app false" case)
  # # when doing a transparent upgrade.  The last worker spawned
  # # will then kill off the old master process with a SIGQUIT.
  # old_pid = "#{server.config[:pid]}.oldbin"
  # if old_pid != server.pid
  #   begin
  #     sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
  #     Process.kill(sig, File.read(old_pid).to_i)
  #   rescue Errno::ENOENT, Errno::ESRCH
  #   end
  # end
  #
  # Throttle the master from forking too quickly by sleeping.  Due
  # to the implementation of standard Unix signal handlers, this
  # helps (but does not completely) prevent identical, repeated signals
  # from being lost when the receiving process is busy.
  # sleep 1
end

after_fork do |server, worker|
  # per-process listener ports for debugging/admin/migrations
  # addr = "127.0.0.1:#{9293 + worker.nr}"
  # server.listen(addr, :tries => -1, :delay => 5, :tcp_nopush => true)

  # the following is *required* for Rails + "preload_app true",
  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.establish_connection

  # if preload_app is true, then you may also want to check and
  # restart any other shared sockets/descriptors such as Memcached,
  # and Redis.  TokyoCabinet file handles are safe to reuse
  # between any number of forked children (assuming your kernel
  # correctly implements pread()/pwrite() system calls)
end

The good news is that the tasks are running only once even with multiple workers

schedule.rb

require 'rufus/scheduler' # http://rufus.rubyforge.org/rufus-scheduler/
scheduler = Rufus::Scheduler.start_new

scheduler.cron '10 5 * * *' do
  Game::MatchSimulator.play_today_matches
  ChampionshipLogic.update_global_ranking
end

# this is the bad behaving
scheduler.every '4h' do
  ManagerLogic.ballance_teams_task
end

:first_at parameter is wonky

I run into this problem, over and over again when I'm trying to use scheduler.every with the :first_at parameter specified.
If I want to run a job every hour but specify that it should run first at 6am, then when my app starts up (lets say its 4pm) ... rufus goes and tries to run every job that SHOULD have run since 6am.

I guess this is the way it was designed, but I think it makes the :first_at parameter unusable.

For example, say I want to send out company wide emails every 2 weeks, but the start day was Jan 2nd 2011 or something like that ... I'd expect rufus to just schedule the next job, but instead it would go out and try to send out emails for all the weeks since the Jan 2nd 2011 ... which is really bad for me.

Is this something you'd be open to changing?
I'd be willing to work on it if you'd take a look at my code.

What's the best way to spec the scheduler?

When defining the tasks to run I really want to spec them to ensure the tasks were actually scheduled correctly.

I have the following in mind, but not sure what's the best way to do it.

class TickTack
  attr_reader :scheduler

 def initialize
   @scheduler = Rufus::PlainScheduler.new # Note that I don't want to actually start it!

    scheduler.cron '0 22 * * 1-5' do
      # every day of the week at 22:00 (10pm)
      Security.activate
    end
 end

  def start!
    scheduler.start
  end
end


# Now I want to spec it similarly to:

describe TickTack do

  def tick
    subject.scheduler.step #????
  end

  it "should activate alarm on the weekdays after 10pm" do
    Timecop.travel Chronic.parse("next monday 22:01")
    Security.should_receive(:activate)
    tick
  end


  it "should not activate alarm on the weekdays before 10pm" do
    Timecop.travel Chronic.parse("next monday 8pm")
    Security.should_not_receive(:activate)
    tick
  end


  it "should not activate alarm on the weekend after 10pm" do
    Timecop.travel Chronic.parse("next sunday 22:01")
    Security.should_not_receive(:activate)
    tick
  end
end

But I don't know if that's a a good way of doing it.

NameError: uninitialized constant

We've been noticing lately (now that we enabled error reporting in our rake tasks) that our rufus scheduler will sometimes (randomly) have an error calling some of the classes and methods in our schedules. Here is an example:

scheduler.every '1d', first_at: start_time, discard_past: true do SomeModule::SomeClass.perform_async "whatever" end

We are passing in a start_time to all of our daily tasks so we can modify them all at once easily, not sure if that could be affecting things.

The error can show up on both the module or the class, such as:

NameError: uninitialized constant SomeModule
or
NameError: uninitialized constant SomeModule::SomeClass

We can't seem to reproduce it but it seems like those classes or modules somehow aren't loaded at the time they are called. This is all in a rake task so maybe that has something to do with it?

Database connection pool

Hi!

I'm using MySQL database and rufus-scheduler version 2.0.8 in my Rails3 app on Jruby 1.5.6 and after some while app runs out of connections and I get AR connection error:
ActiveRecord::ConnectionTimeoutError (could not obtain a database
connection within 5 seconds. The max pool size is currently 5; consider
increasing it.)

I decided to add ActiveRecord::Base.verify_active_connections!
ActiveRecord::Base.connection_pool.clear_stale_cached_connections!
to rufus jobs, but the problem still remains.

I've increased pool size to 90 in database.yml, and that's already an overkill.

Gems:
actionmailer (3.0.3)
actionpack (3.0.3)
activemodel (3.0.3)
activerecord (3.0.3)
activerecord-jdbc-adapter (1.1.1)
activerecord-jdbcmysql-adapter (1.1.1)
activeresource (3.0.3)
activesupport (3.0.3)
rack (1.2.1)
rack-mount (0.6.13)
rack-test (0.5.7)
rails (3.0.3)
rake (0.8.7)
rufus-scheduler (2.0.8)
savon (0.7.9)

Error:

2011-04-06 11:47:28,577 INFO STDOUT scheduler caught exception :
2011-04-06 11:47:28,577 INFO STDOUT undefined method _run_checkin_callbacks' for nil:NilClass 2011-04-06 11:47:28,578 INFO [STDOUT] (Thread-153) /opt/jboss-6.0.0.Final/server/default/tmp/vfs/automount27da01024fe0922c/ROOT.war-511a30acba8a24df/WEB-INF/gems/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:216:incheckin'
2011-04-06 11:47:28,578 INFO STDOUT classpath:/META-INF/jruby.home/lib/ruby/1.8/monitor.rb:191:in mon_synchronize' 2011-04-06 11:47:28,578 INFO [STDOUT] (Thread-153) /opt/jboss-6.0.0.Final/server/default/tmp/vfs/automount27da01024fe0922c/ROOT.war-511a30acba8a24df/WEB-INF/gems/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:215:incheckin'
2011-04-06 11:47:28,578 INFO STDOUT /opt/jboss-6.0.0.Final/server/default/tmp/vfs/automount27da01024fe0922c/ROOT.war-511a30acba8a24df/WEB-INF/gems/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:162:in clear_stale_cached_connections!' 2011-04-06 11:47:28,578 INFO [STDOUT] (Thread-153) /opt/jboss-6.0.0.Final/server/default/tmp/vfs/automount27da01024fe0922c/ROOT.war-511a30acba8a24df/WEB-INF/gems/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:161:ineach'
2011-04-06 11:47:28,578 INFO STDOUT /opt/jboss-6.0.0.Final/server/default/tmp/vfs/automount27da01024fe0922c/ROOT.war-511a30acba8a24df/WEB-INF/gems/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:161:in clear_stale_cached_connections!' 2011-04-06 11:47:28,579 INFO [STDOUT] (Thread-153) /opt/jboss-6.0.0.Final/server/default/tmp/vfs/automount27da01024fe0922c/ROOT.war-511a30acba8a24df/WEB-INF/gems/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:149:inverify_active_connections!'
2011-04-06 11:47:28,579 INFO STDOUT /opt/jboss-6.0.0.Final/server/default/tmp/vfs/automount27da01024fe0922c/ROOT.war-511a30acba8a24df/WEB-INF/gems/gems/activesupport-3.0.3/lib/active_support/core_ext/module/synchronization.rb:40:in verify_active_connections_with_synchronization!' 2011-04-06 11:47:28,579 INFO [STDOUT] (Thread-153) classpath:/META-INF/jruby.home/lib/ruby/1.8/monitor.rb:191:inmon_synchronize'
2011-04-06 11:47:28,579 INFO STDOUT /opt/jboss-6.0.0.Final/server/default/tmp/vfs/automount27da01024fe0922c/ROOT.war-511a30acba8a24df/WEB-INF/gems/gems/activesupport-3.0.3/lib/active_support/core_ext/module/synchronization.rb:39:in verify_active_connections_with_synchronization!' 2011-04-06 11:47:28,579 INFO [STDOUT] (Thread-153) /opt/jboss-6.0.0.Final/server/default/tmp/vfs/automount27da01024fe0922c/ROOT.war-511a30acba8a24df/WEB-INF/gems/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:307:inverify_active_connections!'
2011-04-06 11:47:28,579 INFO STDOUT /opt/jboss-6.0.0.Final/server/default/tmp/vfs/automount27da01024fe0922c/ROOT.war-511a30acba8a24df/WEB-INF/gems/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:307:in each_value' 2011-04-06 11:47:28,579 INFO [STDOUT] (Thread-153) /opt/jboss-6.0.0.Final/server/default/tmp/vfs/automount27da01024fe0922c/ROOT.war-511a30acba8a24df/WEB-INF/gems/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:307:inverify_active_connections!'
2011-04-06 11:47:28,580 INFO STDOUT /opt/jboss-6.0.0.Final/server/default/tmp/vfs/automount27da01024fe0922c/ROOT.war-511a30acba8a24df/WEB-INF/gems/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/connection_specification.rb:109:in verify_active_connections!' 2011-04-06 11:47:28,580 INFO [STDOUT] (Thread-153) /opt/jboss-6.0.0.Final/server/default/tmp/vfs/automount27da01024fe0922c/ROOT.war-511a30acba8a24df/WEB-INF/lib/rufus_jobs.rb:226:inperform'

  1. line is : ActiveRecord::Base.verify_active_connections!

Seems similar to this issue : http://stackoverflow.com/questions/2617617/cant-establish-a-db-connection-maybe-threads-related

No way to get real next run time when job will be executed

I need to know 'real' next run time when job will be executed.
I know that job has next_time, but it doesn't take in consideration if job took longer time to complete than it's schedule time. From the code I see that determine_at can return 'real' next time, but it's protected in some job classes. Is it possible to unprotect this method?

rufus-scheduler throws exceptions during tests and on irb console

Hello,

I started rufus-scheduler according to the tutorial on http://intridea.com/2009/2/13/dead-simple-task-scheduling-in-rails?blog=company.

After installing, whenever I run tests, or start the console, I get exceptions like the following:

=================================================================================> nil
>> 
================================================================================?> 
================================================================================
?> ^D================================================================================
>> ^D================================================================================
scheduler caught exception :================================================================================
scheduler caught exception :================================================================================
scheduler caught exception :
=> nil
================================================================================
scheduler caught exception :
killed thread
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/monitor.rb:295:in `wakeup'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/monitor.rb:295:in `mon_release'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/monitor.rb:228:in `mon_exit'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/monitor.rb:244:in `synchronize'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:183:in `checkout'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:98:in `connection'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:326:in `retrieve_connection'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract/connection_specification.rb:123:in `retrieve_connection'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract/connection_specification.rb:115:in `connection'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:3113:in `quoted_table_name'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:1684:in `construct_finder_sql'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:1548:in `find_every'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:615:in `find'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:635:in `all'
/Users/Jens/Sites/mysite/app/models/messaging.rb:70:in `do_schedule'
/Users/Jens/Sites/mysite/config/initializers/start_scheduler.rb:10
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/jobs.rb:165:in `call'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/jobs.rb:165:in `trigger_block'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/jobs.rb:132:in `trigger'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:327:in `call'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:327:in `trigger_job'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:327:in `initialize'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:327:in `new'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:327:in `trigger_job'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/jobs.rb:122:in `send'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/jobs.rb:122:in `trigger'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/jobs.rb:253:in `trigger'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/jobqueues.rb:60:in `trigger_matching_jobs'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:283:in `step'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:347:in `start'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:345:in `loop'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:345:in `start'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:344:in `initialize'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:344:in `new'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:344:in `start'
/Users/Jens/Sites/mysite/vendor/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:115:in `start_new'
/Users/Jens/Sites/mysite/config/initializers/start_scheduler.rb:6
/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:145:in `load_without_new_constant_marking'
/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:145:in `load'
/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:145:in `load'
/Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/initializer.rb:622:in `load_application_initializers'
/Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/initializer.rb:621:in `each'
/Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/initializer.rb:621:in `load_application_initializers'
/Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/initializer.rb:176:in `process'
/Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/initializer.rb:113:in `send'
/Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/initializer.rb:113:in `run'
/Users/Jens/Sites/mysite/config/environment.rb:31
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `require'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/irb/init.rb:253:in `load_modules'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/irb/init.rb:251:in `each'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/irb/init.rb:251:in `load_modules'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/irb/init.rb:21:in `setup'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/irb.rb:54:in `start'
/usr/bin/irb:13
================================================================================

Any ideas what this might be and/or how I can avoid it?

Thank you!

Jens

Scheduler is not running crons

Hi, with the new releases today 2.0.20 and 2.0.21 my crons are not getting executed. Just wondering if someone else experienced this issue. Maybe it is just an obsolete configuration, which I'm going to check later.

2.0.19 seem to run stable

cron error

when set cron to 0 7-23/2 * * * , I get error:

E:/dev/env/Ruby186/lib/ruby/gems/1.8/gems/rufus-scheduler-2.0.6/lib/rufus/sc/cronline.rb:211:in `Integer': invalid value for Integer: "23/" (ArgumentError)
    from E:/dev/env/Ruby186/lib/ruby/gems/1.8/gems/rufus-scheduler-2.0.6/li/rufus/sc/cronline.rb:211:in `parse_range'
    from E:/dev/env/Ruby186/lib/ruby/gems/1.8/gems/rufus-scheduler-2.0.6/lib/rufus/sc/cronline.rb:177:in `parse_item'
    from E:/dev/env/Ruby186/lib/ruby/gems/1.8/gems/rufus-scheduler-2.0.6/lib/rufus/sc/cronline.rb:64:in `initialize'
    from E:/dev/env/Ruby186/lib/ruby/gems/1.8/gems/rufus-scheduler-2.0.6/lib/rufus/sc/jobs.rb:319:in `new'
    from E:/dev/env/Ruby186/lib/ruby/gems/1.8/gems/rufus-scheduler-2.0.6/lib/rufus/sc/jobs.rb:319:in `initialize'
    from E:/dev/env/Ruby186/lib/ruby/gems/1.8/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:174:in `new'
    from E:/dev/env/Ruby186/lib/ruby/gems/1.8/gems/rufus-scheduler-2.0.6/lib/rufus/sc/scheduler.rb:174:in `cron'
    from test.rb:19

There should be a way to tell the scheduler to exit, and then to wait for it to do so

The docs say that if you run the scheduler in Rails or a daemon-like process, then there's no need to call #join. But that is not true. If the Rails process is shut down (e.g. because Phusion Passenger idle cleans a process, or because you sent SIGTERM to Unicorn) then the main thread should wait for the scheduler thread to exit. Otherwise, the process may terminate while the scheduler is in the middle of working.

There should be a good API for telling the scheduler to exit, and then to wait for that.

Runtime Exception in Ruby 2.0.0

After upgrading from Ruby 1.9.3 -> 2.0.0 I did run a test with three scheduled jobs (every: 10 sec)

The following exception has been thrown after a runtime of 4,5 h.

/home/mario/.rvm/gems/ruby-2.0.0-p0/gems/rufus-scheduler-2.0.17/lib/rufus/sc/jobs.rb:219: [BUG] pthread_mutex_lock: Invalid argument (EINVAL)
ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-linux]

-- Control frame information -----------------------------------------------
c:0008 p:---- s:0023 e:000022 CFUNC :raise
c:0007 p:0031 s:0019 e:000018 BLOCK /home/mario/.rvm/gems/ruby-2.0.0-p0/gems/rufus-scheduler-2.0.17/lib/rufus/sc/jobs.rb:219 [FINISH]
c:0006 p:---- s:0017 e:000016 CFUNC :call
c:0005 p:0019 s:0013 e:000012 METHOD /home/mario/.rvm/gems/ruby-2.0.0-p0/gems/rufus-scheduler-2.0.17/lib/rufus/sc/jobs.rb:231
c:0004 p:0047 s:0010 e:000009 BLOCK /home/mario/.rvm/gems/ruby-2.0.0-p0/gems/rufus-scheduler-2.0.17/lib/rufus/sc/jobs.rb:191 [FINISH]
c:0003 p:---- s:0007 e:000006 CFUNC :call
c:0002 p:0008 s:0004 e:000003 BLOCK /home/mario/.rvm/gems/ruby-2.0.0-p0/gems/rufus-scheduler-2.0.17/lib/rufus/sc/scheduler.rb:416 [FINISH]
c:0001 p:---- s:0002 e:000001 TOP [FINISH]

/home/mario/.rvm/gems/ruby-2.0.0-p0/gems/rufus-scheduler-2.0.17/lib/rufus/sc/scheduler.rb:416:in block in trigger_job' /home/mario/.rvm/gems/ruby-2.0.0-p0/gems/rufus-scheduler-2.0.17/lib/rufus/sc/scheduler.rb:416:incall'
/home/mario/.rvm/gems/ruby-2.0.0-p0/gems/rufus-scheduler-2.0.17/lib/rufus/sc/jobs.rb:191:in block in trigger' /home/mario/.rvm/gems/ruby-2.0.0-p0/gems/rufus-scheduler-2.0.17/lib/rufus/sc/jobs.rb:231:intrigger_block'
/home/mario/.rvm/gems/ruby-2.0.0-p0/gems/rufus-scheduler-2.0.17/lib/rufus/sc/jobs.rb:231:in call' /home/mario/.rvm/gems/ruby-2.0.0-p0/gems/rufus-scheduler-2.0.17/lib/rufus/sc/jobs.rb:219:inblock in trigger'
/home/mario/.rvm/gems/ruby-2.0.0-p0/gems/rufus-scheduler-2.0.17/lib/rufus/sc/jobs.rb:219:in `raise'

-- C level backtrace information -------------------------------------------
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1aee68) [0x7f900cf01e68] vm_dump.c:647
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x6a247) [0x7f900cdbd247] error.c:283
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(rb_bug+0xb3) [0x7f900cdbdf93] error.c:302
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(rb_bug_errno+0x3a) [0x7f900cdbdfda] error.c:320
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1b961a) [0x7f900cf0c61a] thread_pthread.c:198
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1998ef) [0x7f900ceec8ef] vm_insnhelper.c:1438
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1a703d) [0x7f900cefa03d] vm_insnhelper.c:1528
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x19e3f4) [0x7f900cef13f4] insns.def:1017
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1a22ba) [0x7f900cef52ba] vm.c:1175
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1a32ae) [0x7f900cef62ae] vm.c:696
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1a32ea) [0x7f900cef62ea] vm.c:715
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x7926d) [0x7f900cdcc26d] proc.c:578
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1998ef) [0x7f900ceec8ef] vm_insnhelper.c:1438
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1a703d) [0x7f900cefa03d] vm_insnhelper.c:1528
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x19e3f4) [0x7f900cef13f4] insns.def:1017
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1a22ba) [0x7f900cef52ba] vm.c:1175
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1a32ae) [0x7f900cef62ae] vm.c:696
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1a32ea) [0x7f900cef62ea] vm.c:715
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x7926d) [0x7f900cdcc26d] proc.c:578
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1998ef) [0x7f900ceec8ef] vm_insnhelper.c:1438
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1a703d) [0x7f900cefa03d] vm_insnhelper.c:1528
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x19e3f4) [0x7f900cef13f4] insns.def:1017
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1a22ba) [0x7f900cef52ba] vm.c:1175
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1a32ae) [0x7f900cef62ae] vm.c:696
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1a32ea) [0x7f900cef62ea] vm.c:715
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1b8850) [0x7f900cf0b850] thread.c:496
/home/mario/.rvm/rubies/ruby-2.0.0-p0/bin/../lib/libruby.so.2.0(+0x1b8bac) [0x7f900cf0bbac] thread_pthread.c:724
/lib/x86_64-linux-gnu/libpthread.so.0(+0x7e9a) [0x7f900c77ee9a]
/lib/x86_64-linux-gnu/libc.so.6(clone+0x6d) [0x7f900ca87ccd] process.c:6619

-- Other runtime information -----------------------------------------------
[...]

Refactor: simplify at/in/every by quickly handing them off to cron

It seems like the at/in/every jobs can all be represented as cron jobs. For example:

every 5s => */5 * * * * *
in 30m => 0 30 0 1 3 2012 (assuming midnight 29th Feb 2012 when created)

"at" is obviously compatible.

Just a thought anyway :) I'm dissecting the code to look at adding support for distributed scheduled jobs, across multiple machines, without worrying about the scheduler running in multiple locations (backed into redis).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.