pax_global_header00006660000000000000000000000064126227173120014515gustar00rootroot0000000000000052 comment=e9a6c8eb0a55bd6cd8f4a18afa98521d7efeaeb8 rufus-scheduler-3.1.10/000077500000000000000000000000001262271731200147175ustar00rootroot00000000000000rufus-scheduler-3.1.10/.gitignore000066400000000000000000000000261262271731200167050ustar00rootroot00000000000000 .rspec Gemfile.lock rufus-scheduler-3.1.10/.travis.yml000066400000000000000000000004461262271731200170340ustar00rootroot00000000000000language: ruby rvm: - 1.8.7 #- 1.9.2 - 1.9.3 #- 2.0.0 - 2.1.1 - 2.2.2 #- jruby-18mode - jruby-19mode #- jruby-20mode #- rbx-18mode #- rbx-19mode #- rbx-20mode script: bundle exec rspec branches: only: - master #except: # - master sudo: false cache: bundler rufus-scheduler-3.1.10/CHANGELOG.txt000066400000000000000000000162471262271731200167610ustar00rootroot00000000000000 = rufus-scheduler CHANGELOG.txt == rufus-scheduler - 3.1.10 released 2015-11-18 - allow for :first_in => 0, gh-179 by https://github.com/JonMcPherson for https://github.com/Shopify/dashing/commit/ea3730fa4 - stop shipping specs in gem == rufus-scheduler - 3.1.9 released 2015-11-12 - fix potential RuntimeError in CronLine#prev_second, by Alexandru https://github.com/alexandru-calinoiu == rufus-scheduler - 3.1.8 released 2015-11-10 - stop jumping eagerly out of DST, fix for one hour jump when leaving DST thanks Alyssa http://github.com/alyssa == rufus-scheduler - 3.1.7 released 2015-10-15 - ack #unscheduled_at in #scheduled?, by Claude https://github.com/claudeatsafe == rufus-scheduler - 3.1.6 released 2015-10-01 - fix job id uniqueness (JRuby), thanks 김성식 https://github.com/kssminus == rufus-scheduler - 3.1.5 released 2015-09-25 - fix for "not a valid cronline" on "mingw" Ruby distributions, gh-166 == rufus-scheduler - 3.1.4 released 2015/08/29 - fix cron issue reported by Jesse https://github.com/jhw-at-prosperworks-com == rufus-scheduler - 3.1.3 released 2015/06/20 - prevent Thread[:rufus_scheduler_time] -> nil, gh-156 - fix inconsistency in Job#start_work_thread == rufus-scheduler - 3.1.2 released 2015/05/23 - avoid cron/:first_at infinite loop, thanks https://github.com/pouellet == rufus-scheduler - 3.1.1 released 2015/04/19 - fix ZoTime.is_timezone? on OSX, thanks https://github.com/yaauie == rufus-scheduler - 3.1.0 released 2015/04/18 - go without tzinfo (and its dependencies) - include @ketan's #next_time improvements - remove 2.x warning message on install == rufus-scheduler - 3.0.9 released 2014/08/30 - fix TZ with underscores, thanks https://github.com/gnilrets - integrate https://github.com/ecin Lock mecha == rufus-scheduler - 3.0.8 released 2014/06/09 - handle TZInfo errors on DST transitions, thanks https://github.com/junhanamaki - implement Scheduler#up? - let schedule and schedule_at use Chronic if present - let Rufus::Scheduler.parse use Chronic if present == rufus-scheduler - 3.0.7 released 2014/03/18 - implement Scheduler #occurrences and #timeline, inspired by kreynolds - implement Job #last_work_time and #mean_work_time - implement Job#count - add more info to the stderr error output (scheduler/tz info) - prevent skipping a day on switch to summertime, gh-114, thanks Matteo == rufus-scheduler - 3.0.6 released 2014/02/14 - avoid "can't be called from trap context" on Ruby 2.0, gh-98 == rufus-scheduler - 3.0.5 released 2014/01/30 - implement Job#call(do_rescue=false), gh-97 - implement :first => :now for repeat jobs, gh-96 == rufus-scheduler - 3.0.4 released 2014/01/19 - make CronLine#frequency faster (to avoid 20s schedule_cron times) == rufus-scheduler - 3.0.3 released 2013/12/12 - CronLine#previous_time fix by Yassen Bantchev (https://github.com/yassenb) - introduce ZookeptScheduler example in the readme - rename #consider_lockfile to #lock and introduce #unlock == rufus-scheduler - 3.0.2 released 2013/10/22 - default :max_work_threads to 28 - fix "rufus rushes to create work threads" issue, thanks Gatis Tomsons - introduce Rufus::Scheduler::NotRunningError, thanks Gatis Tomsons == rufus-scheduler - 3.0.1 released 2013/10/19 - fix post_install_message, thanks Ted Pennings - bring back .parse_time_string and .parse_duration_string == rufus-scheduler - 3.0.0 released 2013/10/02 - complete rewrite. - introduce scheduler.interval('10s') { ... } == rufus-scheduler - 2.0.24 released 2013/09/02 - lowered tzinfo dependency to >= 0.3.22 http://stackoverflow.com/questions/18551970 == rufus-scheduler - 2.0.23 released 2013/07/26 - mutex vs timeout fix by Tobias Kraze == rufus-scheduler - 2.0.22 released 2013/07/16 - parse "/10 * * * *" again (like <= 2.0.19 did), thanks @skrd == rufus-scheduler - 2.0.21 released 2013/07/15 - add license (MIT) to gemspec file == rufus-scheduler - 2.0.20 released 2013/07/15 - add Rufus::Scheduler.new (so that rs 3.0 quickstarts are OK with 2.0.20) - implement CronLine#previous_time(now=Time.now) (Idea Matteo Cerutti) - throw ArgumentError for invalid cron lines (Thanks Aimee Rose) - cron 0 vs 24 hour case straightening (Thanks Aimee Rose) - support for sun#L or sun#-2 in cron lines == rufus-scheduler - 2.0.19 released 2013/05/07 - raise ArgumentError on <= 0.0 "every" frequency (Thanks Lucy Fu) - support multiple mutexes (Thanks Rainux Luo) == rufus-scheduler - 2.0.18 released 2013/03/06 - support for "L" in cron lines (Thanks Andrew Davey) - support for negative time strings (Thanks Danny "northox" Fullerton) - reject invalid weekdays (Thanks pazustep) == rufus-scheduler - 2.0.17 released 2012/06/14 - @andrehjr patch to make it work on Ruby 1.9.3 - raises ArgumentError on unknown/unsupported options (Idea Tero Tilus) == rufus-scheduler - 2.0.16 released 2011/12/31 - hardened Rufus.parse_time_string - running job thread: getting rid of the job pointer once job is done == rufus-scheduler - 2.0.15 released 2011/12/20 - Scheduler#running_jobs (Thanks Louis Coilliot) == rufus-scheduler - 2.0.14 released 2011/12/11 - Job #pause and #resume - Scheduler #pause(job_or_job_id) and #resume(job_or_job_id) - Scheduler#unschedule(job_or_job_id) == rufus-scheduler - 2.0.13 released 2011/11/14 - cron lines now OK with "09". Thanks Anthony Lewis == rufus-scheduler - 2.0.12 released 2011/10/28 - hardened exception handling. Thanks Sam Gibson - accepting #handle_exception, #log_exception or #on_exception - scheduler.in '1s', :mutex => 'that_mutex_name' == rufus-scheduler - 2.0.11 released 2011/09/30 - require 'rufus-scheduler' works == rufus-scheduler - 2.0.10 released 2011/06/26 - every and allow_overlapping now surviving exceptions. Thanks sha1dy == rufus-scheduler - 2.0.9 released 2011/04/22 - Scheduler#first_at and :discard_past => true. Thanks concept47 - Scheduler#cron and monthdays (sun#2 or mon#1) - Scheduler#unschedule_by_tag(t) == rufus-scheduler - 2.0.8 released 2010/12/31 - issue with cron '0 7-23/2 * * *' fixed. Thanks Pickerel == rufus-scheduler - 2.0.7 released 2010/11/09 - :allow_overlapping => false, thanks Adam Davies - cron and timezones, thanks Tanzeeb Khalili - Scheduler#trigger_threads, thanks Tim Uckun == rufus-scheduler - 2.0.6 released 2010/05/01 - timeout jobs not outliving their parent job anymore, thanks Joel Wood == rufus-scheduler - 2.0.5 released 2010/03/02 - fixed parse_time_string(s) issue, thanks Gonzalo Suarez == rufus-scheduler - 2.0.4 released 2010/02/12 - addressing issue with every and timeout, thanks Tony Day == rufus-scheduler - 2.0.3 released 2009/11/04 - made sure Schedulables with a call(job) method were OK when passed as second parameter (thanks Nate Wiger) == rufus-scheduler - 2.0.2 released 2009/10/31 - unified JobQueue and CronJobQueue, and handed @last_second management to the latter - #trigger_block method for easier override - passing :job => job among Schedulable trigger parameters == rufus-scheduler - 2.0.1 released 2009/05/07 == rufus-scheduler - 2.0.0 released 2009/05/07 ... - initial release (was openwferu-scheduler before that) rufus-scheduler-3.1.10/CREDITS.txt000066400000000000000000000115541262271731200165630ustar00rootroot00000000000000 = CREDITS.txt == Contributors - Jon McPherson (https://github.com/JonMcPherson) :first_in => 0 back - Calinoiu Alexandru Nicolae (https://github.com/alexandru-calinoiu) CronLine#prev_second fix - Alyssa Pohahau (https://github.com/alyssa) out of DST transition specs - Claude Vessaz (https://github.com/claudeatsafe) ack #unscheduled_at in #scheduled? - 김성식 (https://github.com/kssminus) job id uniqueness effort - Jesse Willet (https://github.com/jhw-at-prosperworks-com) cron vs "*/10" - Pascal Ouellet (https://github.com/pouellet) Scheduler#timeline loop fix - Ryan Biesemeyer (https://github.com/yaauie) ZoTime.is_timezone? on OSX - Ketan Padegaonkar (https://github.com/ketan) .brute_frequency improvement - Gabriel Gilder (https://github.com/ggilder) LA DST specs - Sterling Paramore (https://github.com/gnilrets) underscore TZ fix - ecin (https://github.com/ecin) new lock mecha - Adam Jonas (https://github.com/adamjonas) migrate specs to "expect" - Yassen Bantchev (https://github.com/yassenb) CronLine#previous_time rewrite - Eric Lindvall (https://github.com/eric) Zookeeper locked example - Ted Pennings (https://github.com/tedpennings) typo in post_install_message - Tobias Kraze (https://github.com/kratob) timeout vs mutex fix - Patrick Farrell (https://github.com/pfarrell) pointing at deprecated start_new - Thomas Sevestre (https://github.com/thomassevestre) :exception option - Matteo Cerutti - last_time / previous_time idea (and initial implementation) - Aimee Rose (https://github.com/AimeeRose) cronline and > 24 - Lucy Fu (https://github.com/lfu) arg error on <= 0 "every" freq - Rainux Luo (https://github.com/rainux) multiple mutexes - Andrew Davey (https://github.com/asdavey) "L" in cron lines - Stig Kleppe-Jørgensen (https://github.com/stigkj) - Danny "northox" Fullerton (https://github.com/northox) negative time strings - Marcus Brito (https://github.com/pazustep) CronLine proofing - André Luis Leal Cardoso Junior (https://github.com/andrehjr) 1.9.3 patch - Anthony Lewis (https://github.com/anthonylewis) cron lines and 09 issue - concept47 (https://github.com/concept47) every and :discard_past - Chris Kampemeier (http://github.com/chrisk) rspec 2.0 refinements - Tanzeeb Khalili (http://github.com/tanzeeb) cron and timezones - Adam Davies (http://github.com/adz), :allow_overlapping => false - Klaas Jan Wierenga, at/every/in stress tests (1.0 and 2.0) - TobyH (http://github.com/tobyh), faster and cleaner CronLine#next_time == Feedback - Suisea - https://github.com/suisea - readme rewording - Radek - http://stackoverflow.com/users/250422 - gh-166 - Patrik Ragnarsson - https://github.com/dentarg - timeout vs nil, gh-156 - twitter @adefilaedward1 - typo in readme - Michael Guymon - https://github.com/mguymon - #next_time vs :first_at - junhanamaki - https://github.com/junhanamaki - #next_time and dst ambiguities - kreynolds (tossrock) - inspiration for #occurrences - Matteo - https://github.com/m4ce - dst and cron issue - Tobias Bielohlawek - https://github.com/rngtng - missing assertion - Joe Taylor and Agis Anastasopoulos - http://stackoverflow.com/questions/21280870 - :first => :now and Job#call - Gatis Tomsons - https://github.io/gacha - heavy work threads and lock errors - https://github.com/joast - missing .to_time_string alias (code and doc) - Tamir Duberstein - https://github.com/tamird - rdoc inaccuracies - Kevin Bouwkamp - https://github.com/bmxpert1 - first_at issues - Daniel Beauchamp - https://github.com/pushmatrix - pre/post trigger callbacks - Arthur Maltson - https://github.com/amaltson - readme fixes - skrd - https://github.com/skrd - "/10 * * * *" cron issue - Hongli Lai - Scheduler#stop(:terminate => true) request - Tero Tilus - raises on unsupported/unknown options - Louis Coilliot - Scheduler#running_jobs - Henrique G. Testa - pause/resume concept - Sam Gibson - https://github.com/samfoo - exception handling hardening - sha1dy - https://github.com/sha1dy - every and overlapping exception issue - Defusal - unschedule_by_tag - pickerel - https://github.com/pickerel - Gonzalo Suarez - parse_time_string(s) issue - Tony Day - http://github.com/tonyday - every and overlapping timeout issue - Nate Wiger (Schedulable call/trigger issue) - Aldric (readme errors) - Kenneth Kalmer (daemon-kit) - Chris Evans, :timeout tests on JRuby - Tim Uckun, :timeout concept - K Liu, for the note about CronLine#next_time - Xianhang Zhang, find_jobs(tag=nil) patch - Yi Wen, for lib/rufus-scheduler.rb - Adam Green and Rael Dornfest for the Taskr breaking issue feedback - Sean Liu, unschedule_every issue - Manfred Usselman (no cronjobs on sundays bug) - Michael Goth, tests with precision > 1s * many people gave feedback previously, see http://openwferu.rubyforge.org/svn/trunk/openwfe-ruby/CREDITS.txt == and finally - many thanks to the author and contributors of the tzinfo gem (http://tzinfo.github.io/) - many thanks to the EventMachine team (especially Aman Gupta) rufus-scheduler-3.1.10/Gemfile000066400000000000000000000000751262271731200162140ustar00rootroot00000000000000 source 'https://rubygems.org' #gem 'tzinfo-data' gemspec rufus-scheduler-3.1.10/LICENSE.txt000066400000000000000000000020761262271731200165470ustar00rootroot00000000000000 Copyright (c) 2005-2015, John Mettraux, jmettraux@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. rufus-scheduler-3.1.10/README.md000066400000000000000000001207341262271731200162050ustar00rootroot00000000000000 # rufus-scheduler [![Build Status](https://secure.travis-ci.org/jmettraux/rufus-scheduler.png)](http://travis-ci.org/jmettraux/rufus-scheduler) [![Gem Version](https://badge.fury.io/rb/rufus-scheduler.png)](http://badge.fury.io/rb/rufus-scheduler) Job scheduler for Ruby (at, cron, in and every jobs). **Note**: maybe are you looking for the [README of rufus-scheduler 2.x](https://github.com/jmettraux/rufus-scheduler/blob/two/README.rdoc)? Quickstart: ```ruby 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 ``` Various forms of scheduling are supported: ```ruby 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.cron '5 0 * * *' do # do something every day, five minutes after midnight # (see "man 5 crontab" in your terminal) end # ... ``` ## non-features Rufus-scheduler (out of the box) is an in-process, in-memory scheduler. It does not persist your schedules. When the process is gone and the scheduler instance with it, the schedules are gone. ## related and similar gems * [whenever](https://github.com/javan/whenever) - let cron call back your Ruby code, trusted and reliable cron drives your schedule * [clockwork](https://github.com/tomykaira/clockwork) - rufus-scheduler inspired gem * [crono](https://github.com/plashchynski/crono) - an in-Rails cron scheduler (please note: rufus-scheduler is not a cron replacement) ## 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](#so-rails). ## 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 on 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). No intention to re-introduce ```:discard_past => false``` in 3.0 for now. * 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" and "thanks" are not swear words. Go read [how to report bugs effectively](http://www.chiark.greenend.org.uk/~sgtatham/bugs.html), twice. Update: [help_help.md](https://gist.github.com/jmettraux/310fed75f568fd731814) might help help you. ### on StackOverflow Use this [form](http://stackoverflow.com/questions/ask?tags=rufus-scheduler+ruby). It'll create a question flagged "rufus-scheduler" and "ruby". Here are the [questions tagged rufus-scheduler](http://stackoverflow.com/questions/tagged/rufus-scheduler). ### on IRC I sometimes haunt #ruote on freenode.net. The channel is not dedicated to rufus-scheduler, so if you ask a question, first mention it's about rufus-scheduler. Please note that I prefer helping over Stack Overflow because it's more searchable than the ruote IRC archive. ### issues Yes, issues can be reported in [rufus-scheduler issues](https://github.com/jmettraux/rufus-scheduler/issues), I'd actually prefer bugs in there. If there is nothing wrong with rufus-scheduler, a [Stack Overflow question](http://stackoverflow.com/questions/ask?tags=rufus-scheduler+ruby) is better. ### faq * [It doesn't work...](http://www.chiark.greenend.org.uk/~sgtatham/bugs.html) * [I want a refund](http://blog.nodejitsu.com/getting-refunds-on-open-source-projects) * [Passenger and rufus-scheduler](http://stackoverflow.com/questions/18108719/debugging-rufus-scheduler/18156180#18156180) * [Passenger and rufus-scheduler (2)](http://stackoverflow.com/questions/21861387/rufus-cron-job-not-working-in-apache-passenger#answer-21868555) ## 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. ```ruby 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. ```ruby 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. ### #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). ```ruby 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 decide based on its input. It returns the Job instance. ```ruby 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. ```ruby scheduler.repeat '10d' do; end.class # => Rufus::Scheduler::EveryJob scheduler.repeat '* * * * *' do; end.class # => Rufus::Scheduler::CronJob ``` (Yes, no combination heres 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 simple the Job instance involved. It might be useful if the job is to be unscheduled for some reason. ```ruby 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: ```ruby 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 respond to #call(), when scheduling: ```ruby 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. ```ruby 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 # => # job.handler.count # => 0 ``` If you want to keep that "block feeling": ```ruby 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 ### :blocking => true By default, jobs are triggered in their own, new thread. When :blocking => true, the job is triggered in the scheduler thread (a new thread is not created). Yes, while the job triggers, the scheduler is not scheduling. ### :overlap => false Since, by default, jobs are triggered in their own new thread, 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 instance is already running. ### :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 to enter (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](https://github.com/rainux) Warning: creating lots of different mutexes is OK. Rufus-scheduler will place them in its Scheduler#mutexes hash... And they won't get garbage collected. ### :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. ```ruby 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, it's the time *after* which the first schedule will trigger. ```ruby 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 make your schedule more readable. Note: it's OK to change the first_at (a Time instance) directly: ```ruby 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 occurence for immediate triggering. Consider: ```ruby 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] ... ``` ### :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. ```ruby 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 make your schedule more readable. Note: it's OK to change the last_at (nil or a Time instance) directly: ```ruby 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. ```ruby 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. ```ruby 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. ```ruby job = scheduler.cron '0 23 * * *' do # ... end # later on... job.times = 10 # 10 days and it will be over ``` ## 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 return Job instances instead of Job ids (Strings). ```ruby 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. ```ruby 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. ```ruby job = scheduler.schedule_in('10d', :tag => 'hello') do; end job.opts # => { :tag => 'hello' } ``` ### original Returns the original schedule. ```ruby 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 else. ```ruby # when passing a block job = scheduler.schedule_in('10d') do # ... end job.handler # => nil job.callable # => # ``` and ```ruby # 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 # => # job.callable # => # ``` ### scheduled_at Returns the Time instance when the job got created. ```ruby 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). k ```ruby job = scheduler.schedule_every('1d') do; end # ... job.scheduled_at # => 2013-07-17 23:48:54 +0900 ``` ### 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). ### 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 a job thanks to them. ```ruby 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. ```ruby job = scheduler.schedule_in('10d') do; end job.tags # => [] job = scheduler.schedule_in('10d', :tag => 'hello') do; end job.tags # => [ 'hello' ] ``` ### []=, [], key? and keys Threads have thread-local variables. Rufus-scheduler jobs have job-local variables. ```ruby 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.keys # => [ :timestamp, :counter ] ``` Job-local variables are thread-safe. ### call Job instances have a #call method. It simply calls the scheduled block or callable immediately. ```ruby 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: ```ruby require 'rufus-scheduler' s = Rufus::Scheduler.new def s.on_error(job, err) p [ 'error in scheduled job', job.class, job.original, err.message ] 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 to 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 ### frequency It returns the shortest interval of time between two potential occurences of the job. For instance: ```ruby Rufus::Scheduler.parse('* * * * *').frequency # ==> 60 Rufus::Scheduler.parse('* * * * * *').frequency # ==> 1 Rufus::Scheduler.parse('5 23 * * *').frequency # ==> 24 * 3600 Rufus::Scheduler.parse('5 * * * *').frequency # ==> 3600 Rufus::Scheduler.parse('10,20,30 * * * *').frequency # ==> 600 Rufus::Scheduler.parse('10,20,30 * * * * *').frequency # ==> 10 ``` It's used to determine if the job frequency is higher than the scheduler frequency (it raises an ArgumentError if that is the case). ### brute_frequency Cron jobs also have a ```#brute_frequency``` method that looks a one year of intervals to determine the shortest delta for the cron. This method can take between 20 to 50 seconds for cron lines that go the second level. ```#frequency``` above, when encountering second level cron lines will take a shortcut to answer as quickly as possible with a usable value. ## looking up jobs ### Scheduler#job(job_id) The scheduler ```#job(job_id)``` method can be used to lookup Job instances. ```ruby 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: ```ruby # # 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 lookup the job later on. ```ruby 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(: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 Let's the current thread join the scheduling thread in rufus-scheduler. The thread comes back when the scheduler gets shut down. ### 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. ```ruby 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. ```ruby 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](#scheduling-handler-instances) and [scheduling handler classes](#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 abundent 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 ```ruby $stderr = File.open('/var/log/myapplication.log', 'ab') ``` or, you can limit that reassignement to the scheduler itself ```ruby 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 ```ruby def scheduler.on_error(job, error) Logger.warn("intercepted error in #{job.id}: #{error.message}") end ``` ## Rufus::Scheduler #on_pre_trigger and #on_post_trigger callbacks One can bind callbacks before and after jobs trigger: ```ruby 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 were the job execution really happens). ### 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. ```ruby 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. ```ruby scheduler = Rufus::Scheduler.new(:frequency => 5) ``` It's OK to use a time string to specify the frequency. ```ruby 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 scheduler 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](#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: ```ruby 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... ```ruby 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](#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. ```ruby scheduler = Rufus::Scheduler.new(:max_work_threads => 77) ``` It's OK to increase the :max_work_threads of a running scheduler. ```ruby 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 singleon instance of the scheduler, initialized the first time this class method is called. ```ruby 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. ```ruby Rufus::Scheduler.singleton(:max_work_threads => 77) Rufus::Scheduler.singleton(:max_work_threads => 277) # no effect ``` The ```.s``` is a shortcut for ```.singleton```. ```ruby Rufus::Scheduler.s.every '10s' { puts "hello, world!" } ``` ## advanced lock schemes As seen above, rufus-scheduler proposes the [:lockfile](#lockfile--mylockfiletxt) system out of the box. If in a group of schedulers only one is supposed to run, the lockfile mecha prevents schedulers that have not set/created the lockfile from running. There are situation where this is not sufficient. By overriding #lock and #unlock, one can customize how his schedulers lock. This example was provided by [Eric Lindvall](https://github.com/eric): ```ruby 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](http://zookeeper.apache.org/) to make sure only one scheduler in a group of distributed schedulers runs. The methods #lock and #unlock are overriden 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](#trigger_lock) and [:scheduler_lock](#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 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 diectly (no need to instantiate a Scheduler). ```ruby 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('* * * * *') # => # ``` It returns a number when the output is a duration and a CronLine 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```: ```ruby 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: ```ruby scheduler.cron('00 12 * * mon#1') do # ... end ``` To schedule something at noon the last Sunday of every month: ```ruby 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: ```ruby require 'rufus-scheduler' Time.now # => 2013-10-26 07:07:08 +0900 Rufus::Scheduler.parse('* * * * mon#1').next_time # => 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: ```ruby require 'rufus-scheduler' Time.now # => 2013-10-26 07:22:09 +0900 Rufus::Scheduler.parse('00 12 L * *').next_time # => 2013-10-31 12:00:00 +0900 ``` ## a note about timezones Cron schedules and at schedules support the specification of a timezone. ```ruby 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") # => 2013-12-12 04:00:00 UTC ``` ## 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: ```ruby # # 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: ```ruby 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](#faq) above. ### rails server -d (Written in reply to https://github.com/jmettraux/rufus-scheduler/issues/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: * http://www.mikeperham.com/2014/09/22/dont-daemonize-your-daemons/ * http://www.mikeperham.com/2014/07/07/use-runit/ 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). ## support see [getting help](#getting-help) above. ## license MIT, see [LICENSE.txt](LICENSE.txt) rufus-scheduler-3.1.10/Rakefile000066400000000000000000000023101262271731200163600ustar00rootroot00000000000000 require 'rubygems' require 'rake' require 'rake/clean' require 'rdoc/task' # # clean CLEAN.include('pkg', 'rdoc') # # test / spec #task :spec => :check_dependencies do task :spec do exec 'rspec spec/' end task :test => :spec task :default => :spec # # gem GEMSPEC_FILE = Dir['*.gemspec'].first GEMSPEC = eval(File.read(GEMSPEC_FILE)) GEMSPEC.validate desc %{ builds the gem and places it in pkg/ } task :build do sh "gem build #{GEMSPEC_FILE}" sh "mkdir -p pkg" sh "mv #{GEMSPEC.name}-#{GEMSPEC.version}.gem pkg/" end desc %{ builds the gem and pushes it to rubygems.org } task :push => :build do sh "gem push pkg/#{GEMSPEC.name}-#{GEMSPEC.version}.gem" end # # rdoc # # make sure to have rdoc 2.5.x to run that Rake::RDocTask.new do |rd| rd.main = 'README.txt' rd.rdoc_dir = "rdoc/#{GEMSPEC.name}" rd.rdoc_files.include('README.rdoc', 'CHANGELOG.txt', 'lib/**/*.rb') rd.title = "#{GEMSPEC.name} #{GEMSPEC.version}" end # # upload_rdoc desc %{ upload the rdoc to rubyforge } task :upload_rdoc => [ :clean, :rdoc ] do account = 'jmettraux@rubyforge.org' webdir = '/var/www/gforge-projects/rufus' sh "rsync -azv -e ssh rdoc/#{GEMSPEC.name} #{account}:#{webdir}/" end rufus-scheduler-3.1.10/TODO.txt000066400000000000000000000137121262271731200162310ustar00rootroot00000000000000 [o] merge schedule_queue and unschedule_queue (and merge [un]schedule steps) [x] OR stop using queue, since we've got the thread-safe JobArray [x] if possible, drop the mutex in JobArray NO, that mutex is necessary for Scheduler#jobs (on JRuby an co)... [o] named mutexes [o] drop the schedule queue, rely on the mutex in JobArray [o] def jobs; (@jobs.to_a + running_jobs).uniq; end [o] replace @unscheduled by @unscheduled_at [o] make sure #jobs doesn't return unscheduled jobs [o] job tags and find_by_tag(t) (as in rs 2.x) [o] require tzinfo anyway (runtime dep) [o] document frequency [o] accept :frequency => '5s' [o] timeout (as in rufus-scheduler 2.x) [o] Rufus::Scheduler#running_jobs (as in rufus-scheduler 2.x) [o] Rufus::Scheduler#terminate_all_jobs [o] Rufus::Scheduler::Job#kill [x] Rufus::Scheduler#kill_all_jobs [o] Rufus::Scheduler#shutdown(:terminate or :kill (or nothing)) [o] RepeatJob #pause / #resume (think about discard past) [o] Rufus::Scheduler.start_new (backward comp) (with deprec note?) [o] pass job to scheduled block? What does rs 2.x do? [o] :first[_in|_at] for RepeatJob [o] :last[_in|_at] for RepeatJob [o] :times for RepeatJob (how many recurrences) [o] fix issue #39 (first_at parses as UTC) [o] about issue #43, raise if cron/every job frequency < scheduler frequency [o] unlock spec/parse_spec.rb:30 "parse datimes with timezones" [o] some kind of Schedulable (Xyz#call(job, time)) [o] add Jruby and Rubinius to Travis [o] make Job #first_at= / #last_at= automatically parse strings? [o] bring in Kratob's spec about mutex vs timeout and adapt 3.0 to it, https://github.com/jmettraux/rufus-scheduler/pull/67 [x] :unschedule_if => lambda { |job| ... } [o] OR look at how it was done in rs 2.0.x, some return value? no, pass the job as arg to the block, then let the block do job.unschedule so, document schedule.every('10d') { |j| j.unschedule if x?() } [x] remove the time in job.trigger(time) [o] add spec for job queued then unscheduled [o] add spec for Scheduler#shutdown and work threads [o] at some point, bring back rbx19 to Travis [o] move the parse/util part of scheduler.rb to util.rb [o] rescue KillSignal in job thread loop to kill just the job [o] add spec for raise if scheduling a job while scheduler is shutting down [o] schedule_in(2.days.from_now) {} at and in could understand each others time parameter, ftw... use the new #parse_to_time? no [o] do repeat jobs reschedule after timing out? yes [o] schedule_interval('20s')? [x] Scheduler#reschedule(job) (new copy of the job) [x] #free_all_work_threads is missing an implementation [x] rescue StandardError :on_error => :crash[_scheduler] :on_error => :ignore :on_error => ... [o] on_error: what about TimeoutError in that scheme? TimeoutError goes to $stderr, like a normal error [o] link to SO for support - sublink to "how to report bugs effectively" [o] link to #ruote for support [x] lockblock? pass a block to teach the scheduler how to lock? is not necessary, @scheduler = Scheduler.new if should_start? the surrounding Ruby code checks [o] introduce job "vars", as in http://stackoverflow.com/questions/18202848/how-to-have-a-variable-that-will-available-to-particular-scheduled-task-whenever or job['key'] Job #[] and #[]=, as with Thread #[] #[]= job-local variables #keys #key? [o] thread-safety for job-local variables? [x] discard past? discard_past => true or => "1d" default would be discard_past => "1m" or scheduler freq * 2 ? jobs would adjust their next_time until it fits the window... ~~ discard past by default [o] expanded block/schedulable (it's "callable") ``` scheduler.every '10m' do def pre return false if Backend.down? # ... end def post # ... end def trigger puts "oh hai!" end end ``` or something like that... ... OR accept a class (and instantiate it the first time) ``` scheduler.every '10m', Class.new do def call(job, time) # ... end end ``` the job contains the instance in its @callable [x] add spec case for corner case in Job#trigger (overlap vs reschedule) !!! [o] rethink job array vs job set for #scheduled? [x] introduce common parent class for EveryJob and IntervalJob [o] create spec/ at_job_spec.rb, repeat_job_spec.rb, cron_job_spec.rb, ... [x] ensure EveryJob do not schedule in the past (it's already like that) [o] CronLine#next_time should return a time with subseconds chopped off [o] drop min work threads setting? [o] thread pool something? Thread upper limit? [o] Rufus::Scheduler.singleton, Rufus::Scheduler.s [o] EveryJob#first_at= and IntervalJob#first_at= should alter @next_time [o] scheduler.schedule duration/time/cron ... for at/in/cron (not every, nor interval) scheduler.repeat time/cron ... for every/cron [o] :lockfile => x, timestamp, process_id, thread_id... warning: have to clean up that file on exit... or does the scheduler timestamps it? [ ] develop lockfile timestamp thinggy ~ if the timestamp is too old (twice the default frequency?) then lock [file] take over... Is that really what we want all the time? [ ] idea: :mutex => x and :skip_on_mutex => true ? would prevent blocking/waiting for the mutex to get available :mutex => [ "mutex_name", true ] :mutex => [ [ "mutex_name", true ], [ "other_mutex_name", false ] ] [ ] bring back EM (but only EM.defer ?) :defer => true (Job or Scheduler or both option?) [ ] prepare a daemon, trust daemon-kit for that [ ] :if => lambda { |job, time| ... } why not? :unless => lambda { ... :block => lambda { ... can help get the block themselves leaner # investigate guards for schedulables... def if_guard; ...; end [ ] scheduler.every '10', Class.new do def call(job, time) # might fail... end def on_error(err, job) # catches... end end ~~~ [ ] scheduler.at('chronic string', chronic_options...) rufus-scheduler-3.1.10/lib/000077500000000000000000000000001262271731200154655ustar00rootroot00000000000000rufus-scheduler-3.1.10/lib/rufus-scheduler.rb000066400000000000000000000000341262271731200211270ustar00rootroot00000000000000 require 'rufus/scheduler' rufus-scheduler-3.1.10/lib/rufus/000077500000000000000000000000001262271731200166315ustar00rootroot00000000000000rufus-scheduler-3.1.10/lib/rufus/scheduler.rb000066400000000000000000000402231262271731200211350ustar00rootroot00000000000000#-- # Copyright (c) 2006-2015, John Mettraux, jmettraux@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'date' if RUBY_VERSION < '1.9.0' require 'time' require 'thread' #require 'tzinfo' module Rufus class Scheduler require 'rufus/scheduler/util' require 'rufus/scheduler/zotime' require 'rufus/scheduler/jobs' require 'rufus/scheduler/cronline' require 'rufus/scheduler/job_array' require 'rufus/scheduler/locks' VERSION = '3.1.10' # # A common error class for rufus-scheduler # class Error < StandardError; end # # This error is thrown when the :timeout attribute triggers # class TimeoutError < Error; end # # For when the scheduler is not running # (it got shut down or didn't start because of a lock) # class NotRunningError < Error; end #MIN_WORK_THREADS = 3 MAX_WORK_THREADS = 28 attr_accessor :frequency attr_reader :started_at attr_reader :thread attr_reader :thread_key attr_reader :mutexes #attr_accessor :min_work_threads attr_accessor :max_work_threads attr_accessor :stderr attr_reader :work_queue def initialize(opts={}) @opts = opts @started_at = nil @paused = false @jobs = JobArray.new @frequency = Rufus::Scheduler.parse(opts[:frequency] || 0.300) @mutexes = {} @work_queue = Queue.new #@min_work_threads = opts[:min_work_threads] || MIN_WORK_THREADS @max_work_threads = opts[:max_work_threads] || MAX_WORK_THREADS @stderr = $stderr @thread_key = "rufus_scheduler_#{self.object_id}" @scheduler_lock = if lockfile = opts[:lockfile] Rufus::Scheduler::FileLock.new(lockfile) else opts[:scheduler_lock] || Rufus::Scheduler::NullLock.new end @trigger_lock = opts[:trigger_lock] || Rufus::Scheduler::NullLock.new # If we can't grab the @scheduler_lock, don't run. @scheduler_lock.lock || return start end # Returns a singleton Rufus::Scheduler instance # def self.singleton(opts={}) @singleton ||= Rufus::Scheduler.new(opts) end # Alias for Rufus::Scheduler.singleton # def self.s(opts={}); singleton(opts); end # Releasing the gem would probably require redirecting .start_new to # .new and emit a simple deprecation message. # # For now, let's assume the people pointing at rufus-scheduler/master # on GitHub know what they do... # def self.start_new fail "this is rufus-scheduler 3.0, use .new instead of .start_new" end def shutdown(opt=nil) @started_at = nil #jobs.each { |j| j.unschedule } # provokes https://github.com/jmettraux/rufus-scheduler/issue/98 @jobs.array.each { |j| j.unschedule } @work_queue.clear if opt == :wait join_all_work_threads elsif opt == :kill kill_all_work_threads end unlock end alias stop shutdown def uptime @started_at ? Time.now - @started_at : nil end def uptime_s self.class.to_duration(uptime) end def join fail NotRunningError.new( 'cannot join scheduler that is not running' ) unless @thread @thread.join end def down? ! @started_at end def up? !! @started_at end def paused? @paused end def pause @paused = true end def resume @paused = false end #-- # scheduling methods #++ def at(time, callable=nil, opts={}, &block) do_schedule(:once, time, callable, opts, opts[:job], block) end def schedule_at(time, callable=nil, opts={}, &block) do_schedule(:once, time, callable, opts, true, block) end def in(duration, callable=nil, opts={}, &block) do_schedule(:once, duration, callable, opts, opts[:job], block) end def schedule_in(duration, callable=nil, opts={}, &block) do_schedule(:once, duration, callable, opts, true, block) end def every(duration, callable=nil, opts={}, &block) do_schedule(:every, duration, callable, opts, opts[:job], block) end def schedule_every(duration, callable=nil, opts={}, &block) do_schedule(:every, duration, callable, opts, true, block) end def interval(duration, callable=nil, opts={}, &block) do_schedule(:interval, duration, callable, opts, opts[:job], block) end def schedule_interval(duration, callable=nil, opts={}, &block) do_schedule(:interval, duration, callable, opts, true, block) end def cron(cronline, callable=nil, opts={}, &block) do_schedule(:cron, cronline, callable, opts, opts[:job], block) end def schedule_cron(cronline, callable=nil, opts={}, &block) do_schedule(:cron, cronline, callable, opts, true, block) end def schedule(arg, callable=nil, opts={}, &block) opts[:_t] = Scheduler.parse(arg, opts) case opts[:_t] when CronLine then schedule_cron(arg, callable, opts, &block) when Time then schedule_at(arg, callable, opts, &block) else schedule_in(arg, callable, opts, &block) end end def repeat(arg, callable=nil, opts={}, &block) opts[:_t] = Scheduler.parse(arg, opts) case opts[:_t] when CronLine then schedule_cron(arg, callable, opts, &block) else schedule_every(arg, callable, opts, &block) end end def unschedule(job_or_job_id) job, job_id = fetch(job_or_job_id) fail ArgumentError.new("no job found with id '#{job_id}'") unless job job.unschedule if job end #-- # jobs methods #++ # Returns all the scheduled jobs # (even those right before re-schedule). # def jobs(opts={}) opts = { opts => true } if opts.is_a?(Symbol) jobs = @jobs.to_a if opts[:running] jobs = jobs.select { |j| j.running? } elsif ! opts[:all] jobs = jobs.reject { |j| j.next_time.nil? || j.unscheduled_at } end tags = Array(opts[:tag] || opts[:tags]).collect { |t| t.to_s } jobs = jobs.reject { |j| tags.find { |t| ! j.tags.include?(t) } } jobs end def at_jobs(opts={}) jobs(opts).select { |j| j.is_a?(Rufus::Scheduler::AtJob) } end def in_jobs(opts={}) jobs(opts).select { |j| j.is_a?(Rufus::Scheduler::InJob) } end def every_jobs(opts={}) jobs(opts).select { |j| j.is_a?(Rufus::Scheduler::EveryJob) } end def interval_jobs(opts={}) jobs(opts).select { |j| j.is_a?(Rufus::Scheduler::IntervalJob) } end def cron_jobs(opts={}) jobs(opts).select { |j| j.is_a?(Rufus::Scheduler::CronJob) } end def job(job_id) @jobs[job_id] end # Returns true if the scheduler has acquired the [exclusive] lock and # thus may run. # # Most of the time, a scheduler is run alone and this method should # return true. It is useful in cases where among a group of applications # only one of them should run the scheduler. For schedulers that should # not run, the method should return false. # # Out of the box, rufus-scheduler proposes the # :lockfile => 'path/to/lock/file' scheduler start option. It makes # it easy for schedulers on the same machine to determine which should # run (the first to write the lockfile and lock it). It uses "man 2 flock" # so it probably won't work reliably on distributed file systems. # # If one needs to use a special/different locking mechanism, the scheduler # accepts :scheduler_lock => lock_object. lock_object only needs to respond # to #lock # and #unlock, and both of these methods should be idempotent. # # Look at rufus/scheduler/locks.rb for an example. # def lock @scheduler_lock.lock end # Sister method to #lock, is called when the scheduler shuts down. # def unlock @trigger_lock.unlock @scheduler_lock.unlock end # Callback called when a job is triggered. If the lock cannot be acquired, # the job won't run (though it'll still be scheduled to run again if # necessary). # def confirm_lock @trigger_lock.lock end # Returns true if this job is currently scheduled. # # Takes extra care to answer true if the job is a repeat job # currently firing. # def scheduled?(job_or_job_id) job, job_id = fetch(job_or_job_id) !! (job && job.unscheduled_at.nil? && job.next_time != nil) end # Lists all the threads associated with this scheduler. # def threads Thread.list.select { |t| t[thread_key] } end # Lists all the work threads (the ones actually running the scheduled # block code) # # Accepts a query option, which can be set to: # * :all (default), returns all the threads that are work threads # or are currently running a job # * :active, returns all threads that are currenly running a job # * :vacant, returns the threads that are not running a job # # If, thanks to :blocking => true, a job is scheduled to monopolize the # main scheduler thread, that thread will get returned when :active or # :all. # def work_threads(query=:all) ts = threads.select { |t| t[:rufus_scheduler_job] || t[:rufus_scheduler_work_thread] } case query when :active then ts.select { |t| t[:rufus_scheduler_job] } when :vacant then ts.reject { |t| t[:rufus_scheduler_job] } else ts end end def running_jobs(opts={}) jobs(opts.merge(:running => true)) end def occurrences(time0, time1, format=:per_job) h = {} jobs.each do |j| os = j.occurrences(time0, time1) h[j] = os if os.any? end if format == :timeline a = [] h.each { |j, ts| ts.each { |t| a << [ t, j ] } } a.sort_by { |(t, j)| t } else h end end def timeline(time0, time1) occurrences(time0, time1, :timeline) end def on_error(job, err) pre = err.object_id.to_s ms = {}; mutexes.each { |k, v| ms[k] = v.locked? } stderr.puts("{ #{pre} rufus-scheduler intercepted an error:") stderr.puts(" #{pre} job:") stderr.puts(" #{pre} #{job.class} #{job.original.inspect} #{job.opts.inspect}") # TODO: eventually use a Job#detail or something like that stderr.puts(" #{pre} error:") stderr.puts(" #{pre} #{err.object_id}") stderr.puts(" #{pre} #{err.class}") stderr.puts(" #{pre} #{err}") err.backtrace.each do |l| stderr.puts(" #{pre} #{l}") end stderr.puts(" #{pre} tz:") stderr.puts(" #{pre} ENV['TZ']: #{ENV['TZ']}") stderr.puts(" #{pre} Time.now: #{Time.now}") stderr.puts(" #{pre} scheduler:") stderr.puts(" #{pre} object_id: #{object_id}") stderr.puts(" #{pre} opts:") stderr.puts(" #{pre} #{@opts.inspect}") stderr.puts(" #{pre} frequency: #{self.frequency}") stderr.puts(" #{pre} scheduler_lock: #{@scheduler_lock.inspect}") stderr.puts(" #{pre} trigger_lock: #{@trigger_lock.inspect}") stderr.puts(" #{pre} uptime: #{uptime} (#{uptime_s})") stderr.puts(" #{pre} down?: #{down?}") stderr.puts(" #{pre} threads: #{self.threads.size}") stderr.puts(" #{pre} thread: #{self.thread}") stderr.puts(" #{pre} thread_key: #{self.thread_key}") stderr.puts(" #{pre} work_threads: #{work_threads.size}") stderr.puts(" #{pre} active: #{work_threads(:active).size}") stderr.puts(" #{pre} vacant: #{work_threads(:vacant).size}") stderr.puts(" #{pre} max_work_threads: #{max_work_threads}") stderr.puts(" #{pre} mutexes: #{ms.inspect}") stderr.puts(" #{pre} jobs: #{jobs.size}") stderr.puts(" #{pre} at_jobs: #{at_jobs.size}") stderr.puts(" #{pre} in_jobs: #{in_jobs.size}") stderr.puts(" #{pre} every_jobs: #{every_jobs.size}") stderr.puts(" #{pre} interval_jobs: #{interval_jobs.size}") stderr.puts(" #{pre} cron_jobs: #{cron_jobs.size}") stderr.puts(" #{pre} running_jobs: #{running_jobs.size}") stderr.puts(" #{pre} work_queue: #{work_queue.size}") stderr.puts("} #{pre} .") rescue => e stderr.puts("failure in #on_error itself:") stderr.puts(e.inspect) stderr.puts(e.backtrace) ensure stderr.flush end protected # Returns [ job, job_id ] # def fetch(job_or_job_id) if job_or_job_id.respond_to?(:job_id) [ job_or_job_id, job_or_job_id.job_id ] else [ job(job_or_job_id), job_or_job_id ] end end def terminate_all_jobs jobs.each { |j| j.unschedule } sleep 0.01 while running_jobs.size > 0 end def join_all_work_threads work_threads.size.times { @work_queue << :sayonara } work_threads.each { |t| t.join } @work_queue.clear end def kill_all_work_threads work_threads.each { |t| t.kill } end #def free_all_work_threads # # work_threads.each { |t| t.raise(KillSignal) } #end def start @started_at = Time.now @thread = Thread.new do while @started_at do unschedule_jobs trigger_jobs unless @paused timeout_jobs sleep(@frequency) end end @thread[@thread_key] = true @thread[:rufus_scheduler] = self @thread[:name] = @opts[:thread_name] || "#{@thread_key}_scheduler" end def unschedule_jobs @jobs.delete_unscheduled end def trigger_jobs now = Time.now @jobs.each(now) do |job| job.trigger(now) end end def timeout_jobs work_threads(:active).each do |t| job = t[:rufus_scheduler_job] to = t[:rufus_scheduler_timeout] ts = t[:rufus_scheduler_time] next unless job && to && ts # thread might just have become inactive (job -> nil) to = to.is_a?(Time) ? to : ts + to next if to > Time.now t.raise(Rufus::Scheduler::TimeoutError) end end def do_schedule(job_type, t, callable, opts, return_job_instance, block) fail NotRunningError.new( 'cannot schedule, scheduler is down or shutting down' ) if @started_at == nil callable, opts = nil, callable if callable.is_a?(Hash) return_job_instance ||= opts[:job] job_class = case job_type when :once opts[:_t] ||= Rufus::Scheduler.parse(t, opts) opts[:_t].is_a?(Time) ? AtJob : InJob when :every EveryJob when :interval IntervalJob when :cron CronJob end job = job_class.new(self, t, opts, block || callable) fail ArgumentError.new( "job frequency (#{job.frequency}) is higher than " + "scheduler frequency (#{@frequency})" ) if job.respond_to?(:frequency) && job.frequency < @frequency @jobs.push(job) return_job_instance ? job : job.job_id end end end rufus-scheduler-3.1.10/lib/rufus/scheduler/000077500000000000000000000000001262271731200206075ustar00rootroot00000000000000rufus-scheduler-3.1.10/lib/rufus/scheduler/cronline.rb000066400000000000000000000272711262271731200227560ustar00rootroot00000000000000#-- # Copyright (c) 2006-2015, John Mettraux, jmettraux@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'set' class Rufus::Scheduler # # A 'cron line' is a line in the sense of a crontab # (man 5 crontab) file line. # class CronLine # The string used for creating this cronline instance. # attr_reader :original attr_reader :seconds attr_reader :minutes attr_reader :hours attr_reader :days attr_reader :months attr_reader :weekdays attr_reader :monthdays attr_reader :timezone def initialize(line) fail ArgumentError.new( "not a string: #{line.inspect}" ) unless line.is_a?(String) @original = line items = line.split @timezone = items.pop if ZoTime.is_timezone?(items.last) fail ArgumentError.new( "not a valid cronline : '#{line}'" ) unless items.length == 5 or items.length == 6 offset = items.length - 5 @seconds = offset == 1 ? parse_item(items[0], 0, 59) : [ 0 ] @minutes = parse_item(items[0 + offset], 0, 59) @hours = parse_item(items[1 + offset], 0, 24) @days = parse_item(items[2 + offset], 1, 31) @months = parse_item(items[3 + offset], 1, 12) @weekdays, @monthdays = parse_weekdays(items[4 + offset]) [ @seconds, @minutes, @hours, @months ].each do |es| fail ArgumentError.new( "invalid cronline: '#{line}'" ) if es && es.find { |e| ! e.is_a?(Fixnum) } end end # Returns true if the given time matches this cron line. # def matches?(time) time = ZoTime.new(time.to_f, @timezone || ENV['TZ']).time return false unless sub_match?(time, :sec, @seconds) return false unless sub_match?(time, :min, @minutes) return false unless sub_match?(time, :hour, @hours) return false unless date_match?(time) true end # Returns the next time that this cron line is supposed to 'fire' # # This is raw, 3 secs to iterate over 1 year on my macbook :( brutal. # (Well, I was wrong, takes 0.001 sec on 1.8.7 and 1.9.1) # # This method accepts an optional Time parameter. It's the starting point # for the 'search'. By default, it's Time.now # # Note that the time instance returned will be in the same time zone that # the given start point Time (thus a result in the local time zone will # be passed if no start time is specified (search start time set to # Time.now)) # # Rufus::Scheduler::CronLine.new('30 7 * * *').next_time( # Time.mktime(2008, 10, 24, 7, 29)) # #=> Fri Oct 24 07:30:00 -0500 2008 # # Rufus::Scheduler::CronLine.new('30 7 * * *').next_time( # Time.utc(2008, 10, 24, 7, 29)) # #=> Fri Oct 24 07:30:00 UTC 2008 # # Rufus::Scheduler::CronLine.new('30 7 * * *').next_time( # Time.utc(2008, 10, 24, 7, 29)).localtime # #=> Fri Oct 24 02:30:00 -0500 2008 # # (Thanks to K Liu for the note and the examples) # def next_time(from=Time.now) time = nil zotime = ZoTime.new(from.to_i + 1, @timezone || ENV['TZ']) loop do time = zotime.time unless date_match?(time) zotime.add((24 - time.hour) * 3600 - time.min * 60 - time.sec) next end unless sub_match?(time, :hour, @hours) zotime.add((60 - time.min) * 60 - time.sec) next end unless sub_match?(time, :min, @minutes) zotime.add(60 - time.sec) next end unless sub_match?(time, :sec, @seconds) zotime.add(next_second(time)) next end break end time end # Returns the previous time the cronline matched. It's like next_time, but # for the past. # def previous_time(from=Time.now) time = nil zotime = ZoTime.new(from.to_i - 1, @timezone || ENV['TZ']) loop do time = zotime.time unless date_match?(time) zotime.substract(time.hour * 3600 + time.min * 60 + time.sec + 1) next end unless sub_match?(time, :hour, @hours) zotime.substract(time.min * 60 + time.sec + 1) next end unless sub_match?(time, :min, @minutes) zotime.substract(time.sec + 1) next end unless sub_match?(time, :sec, @seconds) zotime.substract(prev_second(time)) next end break end time end # Returns an array of 6 arrays (seconds, minutes, hours, days, # months, weekdays). # This method is used by the cronline unit tests. # def to_array [ toa(@seconds), toa(@minutes), toa(@hours), toa(@days), toa(@months), toa(@weekdays), toa(@monthdays), @timezone ] end # Returns a quickly computed approximation of the frequency for this # cron line. # # #brute_frequency, on the other hand, will compute the frequency by # examining a whole year, that can take more than seconds for a seconds # level cron... # def frequency return brute_frequency unless @seconds && @seconds.length > 1 secs = toa(@seconds) secs[1..-1].inject([ secs[0], 60 ]) { |(prev, delta), sec| d = sec - prev [ sec, d < delta ? d : delta ] }[1] end # Returns the shortest delta between two potential occurences of the # schedule described by this cronline. # # . # # For a simple cronline like "*/5 * * * *", obviously the frequency is # five minutes. Why does this method look at a whole year of #next_time ? # # Consider "* * * * sun#2,sun#3", the computed frequency is 1 week # (the shortest delta is the one between the second sunday and the third # sunday). This method takes no chance and runs next_time for the span # of a whole year and keeps the shortest. # # Of course, this method can get VERY slow if you call on it a second- # based cronline... # # Since it's a rarely used method, I haven't taken the time to make it # smarter/faster. # # One obvious improvement would be to cache the result once computed... # # See https://github.com/jmettraux/rufus-scheduler/issues/89 # for a discussion about this method. # def brute_frequency delta = 366 * DAY_S t0 = previous_time(Time.local(2000, 1, 1)) loop do break if delta <= 1 break if delta <= 60 && @seconds && @seconds.size == 1 t1 = next_time(t0) d = t1 - t0 delta = d if d < delta break if @months == nil && t1.month == 2 break if t1.year >= 2001 t0 = t1 end delta end def next_second(time) secs = toa(@seconds) return secs.first + 60 - time.sec if time.sec > secs.last secs.shift while secs.first < time.sec secs.first - time.sec end def prev_second(time) secs = toa(@seconds) return time.sec + 60 - secs.last if time.sec < secs.first secs.pop while time.sec < secs.last time.sec - secs.last end protected def sc_sort(a) a.sort_by { |e| e.is_a?(String) ? 61 : e.to_i } end if RUBY_VERSION >= '1.9' def toa(item) item == nil ? nil : item.to_a end else def toa(item) item.is_a?(Set) ? sc_sort(item.to_a) : item end end WEEKDAYS = %w[ sun mon tue wed thu fri sat ] DAY_S = 24 * 3600 WEEK_S = 7 * DAY_S def parse_weekdays(item) return nil if item == '*' items = item.downcase.split(',') weekdays = nil monthdays = nil items.each do |it| if m = it.match(/^(.+)#(l|-?[12345])$/) fail ArgumentError.new( "ranges are not supported for monthdays (#{it})" ) if m[1].index('-') expr = it.gsub(/#l/, '#-1') (monthdays ||= []) << expr else expr = it.dup WEEKDAYS.each_with_index { |a, i| expr.gsub!(/#{a}/, i.to_s) } fail ArgumentError.new( "invalid weekday expression (#{it})" ) if expr !~ /^0*[0-7](-0*[0-7])?$/ its = expr.index('-') ? parse_range(expr, 0, 7) : [ Integer(expr) ] its = its.collect { |i| i == 7 ? 0 : i } (weekdays ||= []).concat(its) end end weekdays = weekdays.uniq.sort if weekdays [ weekdays, monthdays ] end def parse_item(item, min, max) return nil if item == '*' r = item.split(',').map { |i| parse_range(i.strip, min, max) }.flatten fail ArgumentError.new( "found duplicates in #{item.inspect}" ) if r.uniq.size < r.size r = sc_sort(r) Set.new(r) end RANGE_REGEX = /^(\*|\d{1,2})(?:-(\d{1,2}))?(?:\/(\d{1,2}))?$/ def parse_range(item, min, max) return %w[ L ] if item == 'L' item = '*' + item if item.match(/^\//) m = item.match(RANGE_REGEX) fail ArgumentError.new( "cannot parse #{item.inspect}" ) unless m sta = m[1] sta = sta == '*' ? min : sta.to_i edn = m[2] edn = edn ? edn.to_i : sta edn = max if m[1] == '*' inc = m[3] inc = inc ? inc.to_i : 1 fail ArgumentError.new( "#{item.inspect} is not in range #{min}..#{max}" ) if sta < min || edn > max r = [] val = sta loop do v = val v = 0 if max == 24 && v == 24 r << v break if inc == 1 && val == edn val += inc break if inc > 1 && val > edn val = min if val > max end r.uniq end def sub_match?(time, accessor, values) value = time.send(accessor) return true if values.nil? return true if values.include?('L') && (time + DAY_S).day == 1 return true if value == 0 && accessor == :hour && values.include?(24) values.include?(value) end def monthday_match?(date, values) return true if values.nil? today_values = monthdays(date) (today_values & values).any? end def date_match?(date) return false unless sub_match?(date, :day, @days) return false unless sub_match?(date, :month, @months) return false unless sub_match?(date, :wday, @weekdays) return false unless monthday_match?(date, @monthdays) true end def monthdays(date) pos = 1 d = date.dup loop do d = d - WEEK_S break if d.month != date.month pos = pos + 1 end neg = -1 d = date.dup loop do d = d + WEEK_S break if d.month != date.month neg = neg - 1 end [ "#{WEEKDAYS[date.wday]}##{pos}", "#{WEEKDAYS[date.wday]}##{neg}" ] end end end rufus-scheduler-3.1.10/lib/rufus/scheduler/job_array.rb000066400000000000000000000043001262271731200231010ustar00rootroot00000000000000#-- # Copyright (c) 2006-2015, John Mettraux, jmettraux@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ module Rufus class Scheduler # # The array rufus-scheduler uses to keep jobs in order (next to trigger # first). # class JobArray def initialize @mutex = Mutex.new @array = [] end def push(job) @mutex.synchronize { @array << job unless @array.index(job) } self end def size @array.size end def each(now, &block) to_a.sort_by { |j| j.next_time || (now + 1) }.each do |job| break unless job.next_time break if job.next_time > now block.call(job) end end def delete_unscheduled @mutex.synchronize { @array.delete_if { |j| j.next_time.nil? || j.unscheduled_at } } end def to_a @mutex.synchronize { @array.dup } end def [](job_id) @mutex.synchronize { @array.find { |j| j.job_id == job_id } } end # Only used when shutting down, directly yields the underlying array. # def array @array end end end end rufus-scheduler-3.1.10/lib/rufus/scheduler/jobs.rb000066400000000000000000000334051262271731200220760ustar00rootroot00000000000000#-- # Copyright (c) 2006-2015, John Mettraux, jmettraux@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ module Rufus class Scheduler #-- # job classes #++ class Job # # Used by Job#kill # class KillSignal < StandardError; end attr_reader :id attr_reader :opts attr_reader :original attr_reader :scheduled_at attr_reader :last_time attr_reader :unscheduled_at attr_reader :tags attr_reader :count attr_reader :last_work_time attr_reader :mean_work_time # next trigger time # attr_accessor :next_time # anything with a #call(job[, timet]) method, # what gets actually triggered # attr_reader :callable # a reference to the instance whose call method is the @callable # attr_reader :handler def initialize(scheduler, original, opts, block) @scheduler = scheduler @original = original @opts = opts @handler = block @callable = if block.respond_to?(:arity) block elsif block.respond_to?(:call) block.method(:call) elsif block.is_a?(Class) @handler = block.new @handler.method(:call) rescue nil else nil end @scheduled_at = Time.now @unscheduled_at = nil @last_time = nil @locals = {} @local_mutex = Mutex.new @id = determine_id fail( ArgumentError, 'missing block or callable to schedule', caller[2..-1] ) unless @callable @tags = Array(opts[:tag] || opts[:tags]).collect { |t| t.to_s } @count = 0 @last_work_time = 0.0 @mean_work_time = 0.0 # tidy up options if @opts[:allow_overlap] == false || @opts[:allow_overlapping] == false @opts[:overlap] = false end if m = @opts[:mutex] @opts[:mutex] = Array(m) end end alias job_id id def trigger(time) set_next_time(time) return if ( opts[:overlap] == false && running? ) return if ( callback(:confirm_lock, time) && callback(:on_pre_trigger, time) ) == false @count += 1 if opts[:blocking] do_trigger(time) else do_trigger_in_thread(time) end end def unschedule @unscheduled_at = Time.now end def threads Thread.list.select { |t| t[:rufus_scheduler_job] == self } end # Kills all the threads this Job currently has going on. # def kill threads.each { |t| t.raise(KillSignal) } end def running? threads.any? end def scheduled? @scheduler.scheduled?(self) end def []=(key, value) @local_mutex.synchronize { @locals[key] = value } end def [](key) @local_mutex.synchronize { @locals[key] } end def key?(key) @local_mutex.synchronize { @locals.key?(key) } end def keys @local_mutex.synchronize { @locals.keys } end #def hash # self.object_id #end #def eql?(o) # o.class == self.class && o.hash == self.hash #end # # might be necessary at some point # Calls the callable (usually a block) wrapped in this Job instance. # # Warning: error rescueing is the responsibity of the caller. # def call(do_rescue=false) do_call(Time.now, do_rescue) end protected def callback(meth, time) return true unless @scheduler.respond_to?(meth) arity = @scheduler.method(meth).arity args = [ self, time ][0, (arity < 0 ? 2 : arity)] @scheduler.send(meth, *args) end def compute_timeout if to = @opts[:timeout] Rufus::Scheduler.parse(to) else nil end end def mutex(m) m.is_a?(Mutex) ? m : (@scheduler.mutexes[m.to_s] ||= Mutex.new) end def do_call(time, do_rescue) args = [ self, time ][0, @callable.arity] @callable.call(*args) rescue StandardError => se fail se unless do_rescue return if se.is_a?(KillSignal) # discard @scheduler.on_error(self, se) # exceptions above StandardError do pass through end def do_trigger(time) t = Time.now # if there are mutexes, t might be really bigger than time Thread.current[:rufus_scheduler_job] = self Thread.current[:rufus_scheduler_time] = t Thread.current[:rufus_scheduler_timeout] = compute_timeout @last_time = t do_call(time, true) ensure @last_work_time = Time.now - Thread.current[:rufus_scheduler_time] @mean_work_time = ((@count - 1) * @mean_work_time + @last_work_time) / @count post_trigger(time) Thread.current[:rufus_scheduler_job] = nil Thread.current[:rufus_scheduler_time] = nil Thread.current[:rufus_scheduler_timeout] = nil end def post_trigger(time) set_next_time(time, true) callback(:on_post_trigger, time) end def start_work_thread thread = Thread.new do Thread.current[@scheduler.thread_key] = true Thread.current[:rufus_scheduler_work_thread] = true loop do job, time = @scheduler.work_queue.pop break if @scheduler.started_at == nil next if job.unscheduled_at begin (job.opts[:mutex] || []).reduce( lambda { job.do_trigger(time) } ) do |b, m| lambda { mutex(m).synchronize { b.call } } end.call rescue KillSignal # simply go on looping end end end thread[@scheduler.thread_key] = true thread[:rufus_scheduler_work_thread] = true # # same as above (in the thead block), # but since it has to be done as quickly as possible. # So, whoever is running first (scheduler thread vs job thread) # sets this information end def do_trigger_in_thread(time) threads = @scheduler.work_threads cur = threads.size vac = threads.select { |t| t[:rufus_scheduler_job] == nil }.size #min = @scheduler.min_work_threads max = @scheduler.max_work_threads que = @scheduler.work_queue.size start_work_thread if vac - que < 1 && cur < max @scheduler.work_queue << [ self, time ] end end class OneTimeJob < Job alias time next_time def occurrences(time0, time1) (time >= time0 && time <= time1) ? [ time ] : [] end protected def determine_id [ self.class.name.split(':').last.downcase[0..-4], @scheduled_at.to_f, @next_time.to_f, self.hash.abs ].map(&:to_s).join('_') end # There is no next_time for one time jobs, hence the false. # def set_next_time(trigger_time, is_post=false) @next_time = is_post ? nil : false end end class AtJob < OneTimeJob def initialize(scheduler, time, opts, block) super(scheduler, time, opts, block) @next_time = opts[:_t] || Rufus::Scheduler.parse_at(time, opts) end end class InJob < OneTimeJob def initialize(scheduler, duration, opts, block) super(scheduler, duration, opts, block) @next_time = @scheduled_at + opts[:_t] || Rufus::Scheduler.parse_in(duration, opts) end end class RepeatJob < Job attr_reader :paused_at attr_reader :first_at attr_accessor :last_at attr_accessor :times def initialize(scheduler, duration, opts, block) super @paused_at = nil @times = opts[:times] fail ArgumentError.new( "cannot accept :times => #{@times.inspect}, not nil or an int" ) unless @times == nil || @times.is_a?(Fixnum) self.first_at = opts[:first] || opts[:first_time] || opts[:first_at] || opts[:first_in] || nil self.last_at = opts[:last] || opts[:last_at] || opts[:last_in] end def first_at=(first) return (@first_at = nil) if first == nil n0 = Time.now n1 = n0 + 0.003 first = n0 if first == :now || first == :immediately || first == 0 @first_at = Rufus::Scheduler.parse_to_time(first) @first_at = n1 if @first_at >= n0 && @first_at < n1 fail ArgumentError.new( "cannot set first[_at|_in] in the past: " + "#{first.inspect} -> #{@first_at.inspect}" ) if @first_at < n0 @first_at end def last_at=(last) @last_at = last ? Rufus::Scheduler.parse_to_time(last) : nil fail ArgumentError.new( "cannot set last[_at|_in] in the past: " + "#{last.inspect} -> #{@last_at.inspect}" ) if last && @last_at < Time.now @last_at end def trigger(time) return if @paused_at return (@next_time = nil) if @times && @times < 1 return (@next_time = nil) if @last_at && time >= @last_at # # TODO: rework that, jobs are thus kept 1 step too much in @jobs super @times -= 1 if @times end def pause @paused_at = Time.now end def resume @paused_at = nil end def paused? @paused_at != nil end def determine_id [ self.class.name.split(':').last.downcase[0..-4], @scheduled_at.to_f, self.hash.abs ].map(&:to_s).join('_') end def occurrences(time0, time1) a = [] nt = @next_time ts = @times loop do break if nt > time1 break if ts && ts <= 0 a << nt if nt >= time0 nt = next_time_from(nt) ts = ts - 1 if ts end a end end # # A parent class of EveryJob and IntervalJob # class EvInJob < RepeatJob def first_at=(first) super @next_time = @first_at end end class EveryJob < EvInJob attr_reader :frequency def initialize(scheduler, duration, opts, block) super(scheduler, duration, opts, block) @frequency = Rufus::Scheduler.parse_in(@original) fail ArgumentError.new( "cannot schedule #{self.class} with a frequency " + "of #{@frequency.inspect} (#{@original.inspect})" ) if @frequency <= 0 set_next_time(nil) end protected def set_next_time(trigger_time, is_post=false) return if is_post @next_time = if @first_at == nil || @first_at < Time.now (trigger_time || Time.now) + @frequency else @first_at end end def next_time_from(time) time + @frequency end end class IntervalJob < EvInJob attr_reader :interval def initialize(scheduler, interval, opts, block) super(scheduler, interval, opts, block) @interval = Rufus::Scheduler.parse_in(@original) fail ArgumentError.new( "cannot schedule #{self.class} with an interval " + "of #{@interval.inspect} (#{@original.inspect})" ) if @interval <= 0 set_next_time(nil) end protected def set_next_time(trigger_time, is_post=false) @next_time = if is_post Time.now + @interval elsif trigger_time.nil? if @first_at == nil || @first_at < Time.now Time.now + @interval else @first_at end else false end end def next_time_from(time) time + @mean_work_time + @interval end end class CronJob < RepeatJob def initialize(scheduler, cronline, opts, block) super(scheduler, cronline, opts, block) @cron_line = opts[:_t] || CronLine.new(cronline) set_next_time(nil) end def frequency @cron_line.frequency end def brute_frequency @cron_line.brute_frequency end protected def set_next_time(trigger_time, is_post=false) @next_time = next_time_from(trigger_time || Time.now) end def next_time_from(time) if @first_at == nil || @first_at <= time @cron_line.next_time(time) else @first_at end end end end end rufus-scheduler-3.1.10/lib/rufus/scheduler/locks.rb000066400000000000000000000045121262271731200222510ustar00rootroot00000000000000#-- # Copyright (c) 2006-2015, John Mettraux, jmettraux@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'fileutils' class Rufus::Scheduler # # A lock that can always be acquired # class NullLock # Locking is always successful. # def lock; true; end def locked?; true; end def unlock; true; end end # # The standard flock mecha, with its own class thanks to @ecin # class FileLock attr_reader :path def initialize(path) @path = path.to_s end # Locking is successful if this Ruby process can create and lock # its lockfile (at the given path). # def lock return true if locked? @lockfile = nil FileUtils.mkdir_p(::File.dirname(@path)) file = File.new(@path, File::RDWR | File::CREAT) locked = file.flock(File::LOCK_NB | File::LOCK_EX) return false unless locked now = Time.now file.print("pid: #{$$}, ") file.print("scheduler.object_id: #{self.object_id}, ") file.print("time: #{now}, ") file.print("timestamp: #{now.to_f}") file.flush @lockfile = file true end def unlock !! (@lockfile && @lockfile.flock(File::LOCK_UN)) end def locked? !! (@lockfile && @lockfile.flock(File::LOCK_NB | File::LOCK_EX)) end end end rufus-scheduler-3.1.10/lib/rufus/scheduler/util.rb000066400000000000000000000200551262271731200221130ustar00rootroot00000000000000#-- # Copyright (c) 2006-2015, John Mettraux, jmettraux@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ module Rufus class Scheduler #-- # time and string methods #++ def self.parse(o, opts={}) opts[:no_error] = true parse_cron(o, opts) || parse_in(o, opts) || # covers 'every' schedule strings parse_at(o, opts) || fail(ArgumentError.new("couldn't parse \"#{o}\"")) end def self.parse_in(o, opts={}) o.is_a?(String) ? parse_duration(o, opts) : o end def self.parse_at(o, opts={}) Rufus::Scheduler::ZoTime.parse(o, opts).time rescue StandardError => se return nil if opts[:no_error] fail se end def self.parse_cron(o, opts) CronLine.new(o) rescue ArgumentError => ae return nil if opts[:no_error] fail ae end def self.parse_to_time(o) t = o t = parse(t) if t.is_a?(String) t = Time.now + t if t.is_a?(Numeric) fail ArgumentError.new( "cannot turn #{o.inspect} to a point in time, doesn't make sense" ) unless t.is_a?(Time) t end DURATIONS2M = [ [ 'y', 365 * 24 * 3600 ], [ 'M', 30 * 24 * 3600 ], [ 'w', 7 * 24 * 3600 ], [ 'd', 24 * 3600 ], [ 'h', 3600 ], [ 'm', 60 ], [ 's', 1 ] ] DURATIONS2 = DURATIONS2M.dup DURATIONS2.delete_at(1) DURATIONS = DURATIONS2M.inject({}) { |r, (k, v)| r[k] = v; r } DURATION_LETTERS = DURATIONS.keys.join DU_KEYS = DURATIONS2M.collect { |k, v| k.to_sym } # Turns a string like '1m10s' into a float like '70.0', more formally, # turns a time duration expressed as a string into a Float instance # (millisecond count). # # w -> week # d -> day # h -> hour # m -> minute # s -> second # M -> month # y -> year # 'nada' -> millisecond # # Some examples: # # Rufus::Scheduler.parse_duration "0.5" # => 0.5 # Rufus::Scheduler.parse_duration "500" # => 0.5 # Rufus::Scheduler.parse_duration "1000" # => 1.0 # Rufus::Scheduler.parse_duration "1h" # => 3600.0 # Rufus::Scheduler.parse_duration "1h10s" # => 3610.0 # Rufus::Scheduler.parse_duration "1w2d" # => 777600.0 # # Negative time strings are OK (Thanks Danny Fullerton): # # Rufus::Scheduler.parse_duration "-0.5" # => -0.5 # Rufus::Scheduler.parse_duration "-1h" # => -3600.0 # def self.parse_duration(string, opts={}) string = string.to_s return 0.0 if string == '' m = string.match(/^(-?)([\d\.#{DURATION_LETTERS}]+)$/) return nil if m.nil? && opts[:no_error] fail ArgumentError.new("cannot parse '#{string}'") if m.nil? mod = m[1] == '-' ? -1.0 : 1.0 val = 0.0 s = m[2] while s.length > 0 m = nil if m = s.match(/^(\d+|\d+\.\d*|\d*\.\d+)([#{DURATION_LETTERS}])(.*)$/) val += m[1].to_f * DURATIONS[m[2]] elsif s.match(/^\d+$/) val += s.to_i elsif s.match(/^\d*\.\d*$/) val += s.to_f elsif opts[:no_error] return nil else fail ArgumentError.new("cannot parse '#{string}' (especially '#{s}')") end break unless m && m[3] s = m[3] end mod * val end class << self #- # for compatibility with rufus-scheduler 2.x #+ alias parse_duration_string parse_duration alias parse_time_string parse_duration end # Turns a number of seconds into a a time string # # Rufus.to_duration 0 # => '0s' # Rufus.to_duration 60 # => '1m' # Rufus.to_duration 3661 # => '1h1m1s' # Rufus.to_duration 7 * 24 * 3600 # => '1w' # Rufus.to_duration 30 * 24 * 3600 + 1 # => "4w2d1s" # # It goes from seconds to the year. Months are not counted (as they # are of variable length). Weeks are counted. # # For 30 days months to be counted, the second parameter of this # method can be set to true. # # Rufus.to_duration 30 * 24 * 3600 + 1, true # => "1M1s" # # If a Float value is passed, milliseconds will be displayed without # 'marker' # # Rufus.to_duration 0.051 # => "51" # Rufus.to_duration 7.051 # => "7s51" # Rufus.to_duration 0.120 + 30 * 24 * 3600 + 1 # => "4w2d1s120" # # (this behaviour mirrors the one found for parse_time_string()). # # Options are : # # * :months, if set to true, months (M) of 30 days will be taken into # account when building up the result # * :drop_seconds, if set to true, seconds and milliseconds will be trimmed # from the result # def self.to_duration(seconds, options={}) h = to_duration_hash(seconds, options) return (options[:drop_seconds] ? '0m' : '0s') if h.empty? s = DU_KEYS.inject('') { |r, key| count = h[key] count = nil if count == 0 r << "#{count}#{key}" if count r } ms = h[:ms] s << ms.to_s if ms s end class << self #- # for compatibility with rufus-scheduler 2.x #+ alias to_duration_string to_duration alias to_time_string to_duration end # Turns a number of seconds (integer or Float) into a hash like in : # # Rufus.to_duration_hash 0.051 # # => { :ms => "51" } # Rufus.to_duration_hash 7.051 # # => { :s => 7, :ms => "51" } # Rufus.to_duration_hash 0.120 + 30 * 24 * 3600 + 1 # # => { :w => 4, :d => 2, :s => 1, :ms => "120" } # # This method is used by to_duration behind the scenes. # # Options are : # # * :months, if set to true, months (M) of 30 days will be taken into # account when building up the result # * :drop_seconds, if set to true, seconds and milliseconds will be trimmed # from the result # def self.to_duration_hash(seconds, options={}) h = {} if seconds.is_a?(Float) h[:ms] = (seconds % 1 * 1000).to_i seconds = seconds.to_i end if options[:drop_seconds] h.delete(:ms) seconds = (seconds - seconds % 60) end durations = options[:months] ? DURATIONS2M : DURATIONS2 durations.each do |key, duration| count = seconds / duration seconds = seconds % duration h[key.to_sym] = count if count > 0 end h end #-- # misc #++ # Produces the UTC string representation of a Time instance # # like "2009/11/23 11:11:50.947109 UTC" # def self.utc_to_s(t=Time.now) "#{t.utc.strftime('%Y-%m-%d %H:%M:%S')}.#{sprintf('%06d', t.usec)} UTC" end # Produces a hour/min/sec/milli string representation of Time instance # def self.h_to_s(t=Time.now) "#{t.strftime('%H:%M:%S')}.#{sprintf('%06d', t.usec)}" end # Debugging tools... # class D def self.h_to_s(t=Time.now); Rufus::Scheduler.h_to_s(t); end end end end rufus-scheduler-3.1.10/lib/rufus/scheduler/zones.rb000066400000000000000000000260351262271731200223000ustar00rootroot00000000000000#-- # Copyright (c) 2006-2015, John Mettraux, jmettraux@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ class Rufus::Scheduler TIMEZONES = %w[ GB NZ UCT EET CET PRC ROC WET GMT EST ROK UTC MST HST MET Zulu Cuba Iran W-SU Eire GMT0 Libya Japan Egypt GMT+0 GMT-0 Israel Poland Navajo Turkey GB-Eire Iceland PST8PDT Etc/UCT CST6CDT NZ-CHAT MST7MDT Jamaica EST5EDT Etc/GMT Etc/UTC US/Samoa Etc/GMT0 Portugal Hongkong Etc/Zulu Singapore Asia/Baku Etc/GMT-9 Etc/GMT+1 Etc/GMT+0 Asia/Aden Etc/GMT+2 Etc/GMT+3 Etc/GMT+4 Etc/GMT+5 Etc/GMT+6 Etc/GMT+7 Etc/GMT+8 Etc/GMT+9 Etc/GMT-0 Etc/GMT-1 Universal Asia/Dili Greenwich Asia/Gaza Etc/GMT-8 Etc/GMT-7 US/Alaska Asia/Oral Etc/GMT-6 Etc/GMT-5 Etc/GMT-4 Asia/Hovd Etc/GMT-3 US/Hawaii Etc/GMT-2 Kwajalein Asia/Omsk Asia/Macao Etc/GMT-14 Asia/Kabul US/Central Etc/GMT-13 US/Arizona Asia/Macau Asia/Qatar Asia/Seoul Asia/Tokyo Asia/Dubai US/Pacific Etc/GMT-12 Etc/GMT-11 Etc/GMT-10 Asia/Dhaka Asia/Dacca Asia/Chita Etc/GMT+12 Etc/GMT+10 Asia/Amman Asia/Aqtau Etc/GMT+11 US/Eastern Asia/Thimbu Asia/Brunei Asia/Tehran Asia/Beirut Europe/Rome Europe/Riga Brazil/Acre Brazil/East Europe/Oslo Brazil/West Africa/Lome Asia/Taipei Asia/Saigon Asia/Riyadh Asia/Aqtobe Asia/Anadyr Europe/Kiev Asia/Almaty Africa/Juba Pacific/Yap US/Aleutian Asia/Muscat US/Mountain Asia/Harbin Asia/Hebron Asia/Manila Asia/Kuwait Asia/Urumqi US/Michigan Indian/Mahe SystemV/EST5 Asia/Kashgar Indian/Cocos Asia/Jakarta Asia/Kolkata Asia/Kuching America/Atka Asia/Irkutsk Pacific/Apia Asia/Magadan Africa/Dakar America/Lima Pacific/Fiji Pacific/Guam Europe/Vaduz Pacific/Niue Asia/Nicosia Africa/Ceuta Pacific/Truk America/Adak Pacific/Wake Africa/Tunis Africa/Cairo Asia/Colombo SystemV/AST4 SystemV/CST6 Asia/Karachi Asia/Rangoon SystemV/MST7 Asia/Baghdad Europe/Malta Africa/Lagos Europe/Minsk SystemV/PST8 Canada/Yukon Asia/Tbilisi America/Nome Asia/Bahrain Africa/Accra Europe/Paris Asia/Bangkok Asia/Bishkek Asia/Thimphu SystemV/YST9 Asia/Yerevan Asia/Yakutsk Europe/Sofia Asia/Ust-Nera Australia/ACT Australia/LHI Europe/Tirane Asia/Tel_Aviv Australia/NSW Africa/Luanda Asia/Tashkent Africa/Lusaka Asia/Shanghai Africa/Malabo Asia/Sakhalin Africa/Maputo Africa/Maseru SystemV/HST10 Africa/Kigali Africa/Niamey Pacific/Samoa America/Sitka Pacific/Palau Pacific/Nauru Pacific/Efate Asia/Makassar Pacific/Chuuk Africa/Harare Africa/Douala America/Aruba America/Thule America/Bahia America/Jujuy America/Belem Asia/Katmandu America/Boise Indian/Comoro Indian/Chagos Asia/Jayapura Europe/Zurich Asia/Istanbul Europe/Zagreb Etc/Greenwich Europe/Warsaw Europe/Vienna Etc/Universal Asia/Dushanbe Europe/Athens Europe/Berlin Africa/Bissau Asia/Damascus Africa/Banjul Europe/Dublin Africa/Bangui Africa/Bamako Europe/Jersey Africa/Asmera Europe/Lisbon Africa/Asmara Europe/London Asia/Ashgabat Asia/Calcutta Europe/Madrid Europe/Monaco Europe/Moscow Europe/Prague Europe/Samara Europe/Skopje Asia/Khandyga Canada/Pacific Africa/Abidjan America/Manaus Asia/Chongqing Asia/Chungking Africa/Algiers America/Maceio US/Pacific-New Africa/Conakry America/La_Paz America/Juneau America/Nassau America/Inuvik Europe/Andorra Africa/Kampala Asia/Ashkhabad Asia/Hong_Kong America/Havana Canada/Eastern Europe/Belfast Canada/Central Australia/West Asia/Jerusalem Africa/Mbabane Asia/Kamchatka America/Virgin America/Guyana Asia/Kathmandu Mexico/General America/Panama Europe/Nicosia America/Denver Europe/Tallinn Africa/Nairobi America/Dawson Europe/Vatican Europe/Vilnius America/Cuiaba Africa/Tripoli Pacific/Wallis Atlantic/Faroe Pacific/Tarawa Pacific/Tahiti Pacific/Saipan Pacific/Ponape America/Cayman America/Cancun Asia/Pontianak Asia/Pyongyang Asia/Vientiane Asia/Qyzylorda Pacific/Noumea America/Bogota Pacific/Midway Pacific/Majuro Asia/Samarkand Indian/Mayotte Pacific/Kosrae Asia/Singapore Indian/Reunion America/Belize America/Regina America/Recife Pacific/Easter Mexico/BajaSur America/Merida Pacific/Chatham Pacific/Fakaofo Pacific/Gambier America/Rosario Asia/Ulan_Bator Indian/Maldives Pacific/Norfolk America/Antigua Asia/Phnom_Penh America/Phoenix America/Caracas America/Cayenne Atlantic/Azores Pacific/Pohnpei Atlantic/Canary America/Chicago Atlantic/Faeroe Africa/Windhoek America/Cordoba America/Creston Africa/Timbuktu America/Curacao Africa/Sao_Tome Africa/Ndjamena SystemV/AST4ADT Europe/Uzhgorod Europe/Tiraspol SystemV/CST6CDT Africa/Monrovia America/Detroit Europe/Sarajevo Australia/Eucla America/Tijuana America/Toronto America/Godthab America/Grenada Europe/Istanbul America/Ojinaga America/Tortola Australia/Perth Europe/Helsinki Australia/South Europe/Guernsey SystemV/EST5EDT Europe/Chisinau SystemV/MST7MDT Europe/Busingen Europe/Budapest Europe/Brussels America/Halifax America/Mendoza America/Noronha America/Nipigon Canada/Atlantic America/Yakutat SystemV/PST8PDT SystemV/YST9YDT Canada/Mountain Africa/Kinshasa Africa/Khartoum Africa/Gaborone Africa/Freetown America/Iqaluit America/Jamaica US/East-Indiana Africa/El_Aaiun America/Knox_IN Africa/Djibouti Africa/Blantyre America/Moncton America/Managua Asia/Choibalsan America/Marigot Australia/North Europe/Belgrade America/Resolute America/Mazatlan Pacific/Funafuti Pacific/Auckland Pacific/Honolulu Pacific/Johnston America/Miquelon America/Santarem Mexico/BajaNorte America/Santiago Antarctica/Troll America/Asuncion America/Atikokan America/Montreal America/Barbados Africa/Bujumbura Pacific/Pitcairn Asia/Ulaanbaatar Indian/Mauritius America/New_York Antarctica/Syowa America/Shiprock Indian/Kerguelen Asia/Novosibirsk America/Anguilla Indian/Christmas Asia/Vladivostok Asia/Ho_Chi_Minh Antarctica/Davis Atlantic/Bermuda Europe/Amsterdam Antarctica/Casey America/St_Johns Atlantic/Madeira America/Winnipeg America/St_Kitts Europe/Volgograd Brazil/DeNoronha Europe/Bucharest Africa/Mogadishu America/St_Lucia Atlantic/Stanley Europe/Stockholm Australia/Currie Europe/Gibraltar Australia/Sydney Asia/Krasnoyarsk Australia/Darwin America/Dominica America/Edmonton America/Eirunepe Europe/Podgorica America/Ensenada Europe/Ljubljana Australia/Hobart Europe/Mariehamn Africa/Lubumbashi America/Goose_Bay Europe/Luxembourg America/Menominee America/Glace_Bay America/Fortaleza Africa/Nouakchott America/Matamoros Pacific/Galapagos America/Guatemala Pacific/Kwajalein Pacific/Marquesas America/Guayaquil Asia/Kuala_Lumpur Europe/San_Marino America/Monterrey Europe/Simferopol America/Araguaina Antarctica/Vostok Europe/Copenhagen America/Catamarca Pacific/Pago_Pago America/Sao_Paulo America/Boa_Vista America/St_Thomas Chile/Continental America/Vancouver Africa/Casablanca Europe/Bratislava Pacific/Enderbury Pacific/Rarotonga Europe/Zaporozhye US/Indiana-Starke Antarctica/Palmer Asia/Novokuznetsk Africa/Libreville America/Chihuahua America/Anchorage Pacific/Tongatapu Antarctica/Mawson Africa/Porto-Novo Asia/Yekaterinburg America/Paramaribo America/Hermosillo Atlantic/Jan_Mayen Antarctica/McMurdo America/Costa_Rica Antarctica/Rothera America/Grand_Turk Atlantic/Reykjavik Atlantic/St_Helena Australia/Victoria Chile/EasterIsland Asia/Ujung_Pandang Australia/Adelaide America/Montserrat America/Porto_Acre Africa/Brazzaville Australia/Brisbane America/Kralendijk America/Montevideo America/St_Vincent America/Louisville Australia/Canberra Australia/Tasmania Europe/Isle_of_Man Europe/Kaliningrad Africa/Ouagadougou America/Rio_Branco Pacific/Kiritimati Africa/Addis_Ababa America/Metlakatla America/Martinique Asia/Srednekolymsk America/Guadeloupe America/Fort_Wayne Australia/Lindeman America/Whitehorse Arctic/Longyearbyen America/Pangnirtung America/Mexico_City America/Los_Angeles America/Rainy_River Atlantic/Cape_Verde Pacific/Guadalcanal Indian/Antananarivo America/El_Salvador Australia/Lord_Howe Africa/Johannesburg America/Tegucigalpa Canada/Saskatchewan America/Thunder_Bay Canada/Newfoundland America/Puerto_Rico America/Yellowknife Australia/Melbourne America/Porto_Velho Australia/Queensland Australia/Yancowinna America/Santa_Isabel America/Blanc-Sablon America/Scoresbysund America/Danmarkshavn Pacific/Port_Moresby Antarctica/Macquarie America/Buenos_Aires Africa/Dar_es_Salaam America/Campo_Grande America/Dawson_Creek America/Indianapolis Pacific/Bougainville America/Rankin_Inlet America/Indiana/Knox America/Lower_Princes America/Coral_Harbour America/St_Barthelemy Australia/Broken_Hill America/Cambridge_Bay America/Indiana/Vevay America/Swift_Current America/Port_of_Spain Antarctica/South_Pole America/Santo_Domingo Atlantic/South_Georgia America/Port-au-Prince America/Bahia_Banderas America/Indiana/Winamac America/Indiana/Marengo America/Argentina/Jujuy America/Argentina/Salta Canada/East-Saskatchewan America/Indiana/Vincennes America/Argentina/Tucuman America/Argentina/Ushuaia Antarctica/DumontDUrville America/Indiana/Tell_City America/Argentina/Mendoza America/Argentina/Cordoba America/Indiana/Petersburg America/Argentina/San_Luis America/Argentina/San_Juan America/Argentina/La_Rioja America/North_Dakota/Center America/Kentucky/Monticello America/North_Dakota/Beulah America/Kentucky/Louisville America/Argentina/Catamarca America/Indiana/Indianapolis America/North_Dakota/New_Salem America/Argentina/Rio_Gallegos America/Argentina/Buenos_Aires America/Argentina/ComodRivadavia ] TIMEZONEs = TIMEZONES.collect(&:downcase) ## ## http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations # #ABBREVIATIONS = %w[ #ACDT ACST ACT ADT AEDT AEST AFT AKDT AKST AMST AMST AMT AMT ART AST AST AWDT #AWST AZOST AZT BDT BIOT BIT BOT BRT BST BST BTT CAT CCT CDT CDT CEDT CEST CET #CHADT CHAST CHOT ChST CHUT CIST CIT CKT CLST CLT COST COT CST CST CST CST CST #CT CVT CWST CXT DAVT DDUT DFT EASST EAST EAT ECT ECT EDT EEDT EEST EET EGST EGT #EIT EST EST FET FJT FKST FKST FKT FNT GALT GAMT GET GFT GILT GIT GMT GST GST #GYT HADT HAEC HAST HKT HMT HOVT HST ICT IDT IOT IRDT IRKT IRST IST IST IST JST #KGT KOST KRAT KST LHST LHST LINT MAGT MART MAWT MDT MET MEST MHT MIST MIT MMT #MSK MST MST MST MUT MVT MYT NCT NDT NFT NPT NST NT NUT NZDT NZST OMST ORAT PDT #PET PETT PGT PHOT PKT PMDT PMST PONT PST PST PYST PYT RET ROTT SAKT SAMT SAST #SBT SCT SGT SLST SRET SRT SST SST SYOT TAHT THA TFT TJT TKT TLT TMT TOT TVT UCT #ULAT USZ1 UTC UYST UYT UZT VET VLAT VOLT VOST VUT WAKT WAST WAT WEDT WEST WET #WIT WST YAKT YEKT Z #].uniq end rufus-scheduler-3.1.10/lib/rufus/scheduler/zotime.rb000066400000000000000000000073561262271731200224560ustar00rootroot00000000000000#-- # Copyright (c) 2006-2015, John Mettraux, jmettraux@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Made in Japan. #++ require 'rufus/scheduler/zones' class Rufus::Scheduler # # Zon{ing|ed}Time, whatever. # class ZoTime attr_accessor :seconds attr_accessor :zone def initialize(s, zone) @seconds = s.to_f @zone = zone end def time in_zone do t = Time.at(@seconds) #if t.isdst # t1 = Time.at(@seconds + 3600) # t = t1 if t.zone != t1.zone && t.hour == t1.hour && t.min == t1.min # # ambiguous TZ (getting out of DST) #else # t.hour # force t to compute itself #end # # jump out of DST as soon as possible, jumps 1h as seen from UTC t.hour # force t to compute itself # # stay in DST as long as possible, no jump seen from UTC t end end def utc time.utc end def add(s) @seconds += s.to_f end def substract(s) @seconds -= s.to_f end def to_f @seconds end #DELTA_TZ_REX = /^[+-][0-1][0-9]:?[0-5][0-9]$/ def self.envtzable?(s) TIMEZONES.include?(s) end def self.parse(str, opts={}) if defined?(::Chronic) && t = ::Chronic.parse(str, opts) return ZoTime.new(t, ENV['TZ']) end begin DateTime.parse(str) rescue fail ArgumentError, "no time information in #{o.inspect}" end if RUBY_VERSION < '1.9.0' zone = nil s = str.gsub(/\S+/) { |m| if envtzable?(m) zone ||= m '' else m end } return nil unless zone.nil? || is_timezone?(zone) zt = ZoTime.new(0, zone || ENV['TZ']) zt.in_zone { zt.seconds = Time.parse(s).to_f } zt.seconds == nil ? nil : zt end def self.is_timezone?(str) return false if str == nil return false if str == '*' return false if str.index('#') # "sun#2", etc... On OSX would go all the way to true return true if Time.zone_offset(str) return !! (::TZInfo::Timezone.get(str) rescue nil) if defined?(::TZInfo) return true if TIMEZONES.include?(str) return true if TIMEZONEs.include?(str) t = ZoTime.new(0, str).time return false if t.zone == '' return false if t.zone == 'UTC' return false if t.utc_offset == 0 && str.start_with?(t.zone) # 3 common fallbacks... return false if RUBY_PLATFORM.include?('java') && ! envtzable?(str) true end def in_zone(&block) current_timezone = ENV['TZ'] ENV['TZ'] = @zone block.call ensure ENV['TZ'] = current_timezone end end end rufus-scheduler-3.1.10/misc/000077500000000000000000000000001262271731200156525ustar00rootroot00000000000000rufus-scheduler-3.1.10/misc/cronline_next_time_cost.rb000066400000000000000000000004111262271731200231100ustar00rootroot00000000000000 $:.unshift('lib') require 'rufus/scheduler' loop do print "> " s = gets cl = Rufus::Scheduler::CronLine.new(s) t = Time.now puts cl.next_time puts "took #{Time.now - t} secs" t = Time.now p cl.frequency puts "took #{Time.now - t} secs" end rufus-scheduler-3.1.10/misc/freq.rb000066400000000000000000000006061262271731200171360ustar00rootroot00000000000000 require 'benchmark' $:.unshift('lib') require 'rufus/scheduler' N = 10 puts puts "Ruby: #{RUBY_PLATFORM} #{RUBY_VERSION}" puts "N is #{N}" puts Benchmark.benchmark(Benchmark::Tms::CAPTION, 31) do |b| cl = Rufus::Scheduler::CronLine.new('*/2 * * * *') b.report('.next_time') do N.times { cl.next_time } end b.report('.frequency') do N.times { cl.frequency } end end rufus-scheduler-3.1.10/misc/gacha_test.rb000066400000000000000000000033141262271731200203020ustar00rootroot00000000000000 # # from @gacha # # in https://github.com/jmettraux/rufus-scheduler/issues/84 # # # Linux 3.2.0-4-amd64 #1 SMP Debian 3.2.46-1+deb7u1 x86_64 GNU/Linux # # # * max work threads default to 28 (was 35) # # ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux] # dies ("Killed") after reaching 22 work threads # # ruby 1.9.3p392 (2013-02-22 revision 39386) [x86_64-linux] # is fine, is pegged at 28 (was 35) # # jruby 1.7.4 (1.9.3p392) 2013-05-16 2390d3b on # OpenJDK 64-Bit Server VM 1.6.0_27-b27 [linux-amd64] # dies ("Killed") after reaching 2 work threads # # ruby 1.8.7 (2012-10-12 patchlevel 371) [x86_64-linux] # is fine, is pegged at 28 (was 35) # # ruby 2.0.0p195 (2013-05-14 revision 40734) [x86_64-linux # dies ("Killed") after reaching 21 work threads # # # * max work threads set at 7 # # ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux] # is pegged at 7, but dies ("Killed") after a while (135 seconds) # # ruby 2.0.0p195 (2013-05-14 revision 40734) [x86_64-linux # is pegged at 7, seems OK (stopped the test after 349 seconds) # puts "Ruby #{RUBY_VERSION}p#{RUBY_PATCHLEVEL}" require 'rufus-scheduler' #s = Rufus::Scheduler.new s = Rufus::Scheduler.new(:max_work_threads => 7) s.every '5s', :overlap => false do puts '.. 1st task started' numbers = (0..5000000).to_a.shuffle numbers.sort puts 'oo 1nd task finished' end s.every '7s', :overlap => false do puts '.. 2nd task started' numbers = (0..5000000).to_a.shuffle numbers.sort puts 'oo 2nd task finished' end start = Time.now loop do p [ :elapsed, (Time.now - start).to_i, :threads, Thread.list.size, :work_threads, s.work_threads.size, :active_work_threads, s.work_threads(:active).size ] sleep 1 end #s.join rufus-scheduler-3.1.10/misc/six_field_cronline_test.rb000077500000000000000000000033141262271731200231010ustar00rootroot00000000000000#!/usr/bin/env ruby # # six_field_cronline_test.rb # # Demonstrates an odd behavior with six-field cronlines. We compare # two schedules which ought to be identical: # # each: 10s # cron: */10 * * * * * # # When we run this with rufus-scheduler 3.1.3, we get something like: # # $ misc/six_field_cronline_test.rb # 0.000: misc/six_field_cronline_test.rb: using rufus-scheduler 3.1.3 # 5.147: cron: '*/10 * * * * *' # 10.296: every: 10s # 15.142: cron: '*/10 * * * * *' # 20.597: every: 10s # 25.128: cron: '*/10 * * * * *' # 30.887: every: 10s # 35.122: cron: '*/10 * * * * *' # 41.185: every: 10s # 51.470: every: 10s # 61.756: every: 10s # 72.051: every: 10s # 82.345: every: 10s # 92.626: every: 10s # 95.059: cron: '*/10 * * * * *' # 102.645: every: 10s # 112.931: every: 10s # 123.230: every: 10s # 133.246: every: 10s # 143.534: every: 10s # 153.821: every: 10s # 155.028: cron: '*/10 * * * * *' # 164.107: every: 10s # ^C # # Note that the cronline gave the expected behavior at first, # triggering every 10s or so. However after a few iterations, it # slows to every 60s. # # author: jhw@prosperworks.com # incept: 2015-08-26 # require 'rufus-scheduler' START_TIME ||= Time.now.to_f def log(last_time, msg) f = Time.now.to_f delta_t = f - START_TIME delta_l = f - last_time printf("%7.3f: +%06.3f %s\n", delta_t, delta_l, msg) $stdout.flush f end puts "#{$0}: using rufus-scheduler #{Rufus::Scheduler::VERSION}" scheduler = Rufus::Scheduler.new elt = START_TIME clt = START_TIME scheduler.every '10s' do elt = log(elt, "every: 10s") end scheduler.cron '*/10 * * * * *' do clt = log(clt, "cron: '*/10 * * * * *'") end scheduler.join rufus-scheduler-3.1.10/misc/tz_all.rb000066400000000000000000000005751262271731200174730ustar00rootroot00000000000000 require 'tzinfo' # if tzinfo-data is installed, tzinfo picks it up # automatically #TZInfo::Timezone.all.each { |tz| puts tz.name } tzs = TZInfo::Timezone.all.sort_by { |tz| tz.name.length } puts "TIMEZONES = %[" l = 0 tzs.each do |tz| if l + tz.name.length > 79 puts; l = 0 elsif l > 0 print ' '; l += 1 end l += tz.name.length print tz.name; end puts "\n]" rufus-scheduler-3.1.10/misc/tz_all.txt000066400000000000000000000220451262271731200177030ustar00rootroot00000000000000 # # Tue Oct 8 06:58:45 JST 2013 # Debian GNU/Linux 7 (tzinfo without tzinfo-data) # # #require 'tzinfo' #TZInfo::Timezone.all.each { |tz| puts tz.name } # Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara Africa/Asmera Africa/Bamako Africa/Bangui Africa/Banjul Africa/Bissau Africa/Blantyre Africa/Brazzaville Africa/Bujumbura Africa/Cairo Africa/Casablanca Africa/Ceuta Africa/Conakry Africa/Dakar Africa/Dar_es_Salaam Africa/Djibouti Africa/Douala Africa/El_Aaiun Africa/Freetown Africa/Gaborone Africa/Harare Africa/Johannesburg Africa/Juba Africa/Kampala Africa/Khartoum Africa/Kigali Africa/Kinshasa Africa/Lagos Africa/Libreville Africa/Lome Africa/Luanda Africa/Lubumbashi Africa/Lusaka Africa/Malabo Africa/Maputo Africa/Maseru Africa/Mbabane Africa/Mogadishu Africa/Monrovia Africa/Nairobi Africa/Ndjamena Africa/Niamey Africa/Nouakchott Africa/Ouagadougou Africa/Porto-Novo Africa/Sao_Tome Africa/Timbuktu Africa/Tripoli Africa/Tunis Africa/Windhoek America/Adak America/Anchorage America/Anguilla America/Antigua America/Araguaina America/Argentina/Buenos_Aires America/Argentina/Catamarca America/Argentina/ComodRivadavia America/Argentina/Cordoba America/Argentina/Jujuy America/Argentina/La_Rioja America/Argentina/Mendoza America/Argentina/Rio_Gallegos America/Argentina/Salta America/Argentina/San_Juan America/Argentina/San_Luis America/Argentina/Tucuman America/Argentina/Ushuaia America/Aruba America/Asuncion America/Atikokan America/Atka America/Bahia America/Bahia_Banderas America/Barbados America/Belem America/Belize America/Blanc-Sablon America/Boa_Vista America/Bogota America/Boise America/Buenos_Aires America/Cambridge_Bay America/Campo_Grande America/Cancun America/Caracas America/Catamarca America/Cayenne America/Cayman America/Chicago America/Chihuahua America/Coral_Harbour America/Cordoba America/Costa_Rica America/Creston America/Cuiaba America/Curacao America/Danmarkshavn America/Dawson America/Dawson_Creek America/Denver America/Detroit America/Dominica America/Edmonton America/Eirunepe America/El_Salvador America/Ensenada America/Fort_Wayne America/Fortaleza America/Glace_Bay America/Godthab America/Goose_Bay America/Grand_Turk America/Grenada America/Guadeloupe America/Guatemala America/Guayaquil America/Guyana America/Halifax America/Havana America/Hermosillo America/Indiana/Indianapolis America/Indiana/Knox America/Indiana/Marengo America/Indiana/Petersburg America/Indiana/Tell_City America/Indiana/Vevay America/Indiana/Vincennes America/Indiana/Winamac America/Indianapolis America/Inuvik America/Iqaluit America/Jamaica America/Jujuy America/Juneau America/Kentucky/Louisville America/Kentucky/Monticello America/Knox_IN America/Kralendijk America/La_Paz America/Lima America/Los_Angeles America/Louisville America/Lower_Princes America/Maceio America/Managua America/Manaus America/Marigot America/Martinique America/Matamoros America/Mazatlan America/Mendoza America/Menominee America/Merida America/Metlakatla America/Mexico_City America/Miquelon America/Moncton America/Monterrey America/Montevideo America/Montreal America/Montserrat America/Nassau America/New_York America/Nipigon America/Nome America/Noronha America/North_Dakota/Beulah America/North_Dakota/Center America/North_Dakota/New_Salem America/Ojinaga America/Panama America/Pangnirtung America/Paramaribo America/Phoenix America/Port-au-Prince America/Port_of_Spain America/Porto_Acre America/Porto_Velho America/Puerto_Rico America/Rainy_River America/Rankin_Inlet America/Recife America/Regina America/Resolute America/Rio_Branco America/Rosario America/Santa_Isabel America/Santarem America/Santiago America/Santo_Domingo America/Sao_Paulo America/Scoresbysund America/Shiprock America/Sitka America/St_Barthelemy America/St_Johns America/St_Kitts America/St_Lucia America/St_Thomas America/St_Vincent America/Swift_Current America/Tegucigalpa America/Thule America/Thunder_Bay America/Tijuana America/Toronto America/Tortola America/Vancouver America/Virgin America/Whitehorse America/Winnipeg America/Yakutat America/Yellowknife Antarctica/Casey Antarctica/Davis Antarctica/DumontDUrville Antarctica/Macquarie Antarctica/Mawson Antarctica/McMurdo Antarctica/Palmer Antarctica/Rothera Antarctica/South_Pole Antarctica/Syowa Antarctica/Vostok Arctic/Longyearbyen Asia/Aden Asia/Almaty Asia/Amman Asia/Anadyr Asia/Aqtau Asia/Aqtobe Asia/Ashgabat Asia/Ashkhabad Asia/Baghdad Asia/Bahrain Asia/Baku Asia/Bangkok Asia/Beirut Asia/Bishkek Asia/Brunei Asia/Calcutta Asia/Choibalsan Asia/Chongqing Asia/Chungking Asia/Colombo Asia/Dacca Asia/Damascus Asia/Dhaka Asia/Dili Asia/Dubai Asia/Dushanbe Asia/Gaza Asia/Harbin Asia/Hebron Asia/Ho_Chi_Minh Asia/Hong_Kong Asia/Hovd Asia/Irkutsk Asia/Istanbul Asia/Jakarta Asia/Jayapura Asia/Jerusalem Asia/Kabul Asia/Kamchatka Asia/Karachi Asia/Kashgar Asia/Kathmandu Asia/Katmandu Asia/Khandyga Asia/Kolkata Asia/Krasnoyarsk Asia/Kuala_Lumpur Asia/Kuching Asia/Kuwait Asia/Macao Asia/Macau Asia/Magadan Asia/Makassar Asia/Manila Asia/Muscat Asia/Nicosia Asia/Novokuznetsk Asia/Novosibirsk Asia/Omsk Asia/Oral Asia/Phnom_Penh Asia/Pontianak Asia/Pyongyang Asia/Qatar Asia/Qyzylorda Asia/Rangoon Asia/Riyadh #Asia/Riyadh87 #Asia/Riyadh88 #Asia/Riyadh89 Asia/Saigon Asia/Sakhalin Asia/Samarkand Asia/Seoul Asia/Shanghai Asia/Singapore Asia/Taipei Asia/Tashkent Asia/Tbilisi Asia/Tehran Asia/Tel_Aviv Asia/Thimbu Asia/Thimphu Asia/Tokyo Asia/Ujung_Pandang Asia/Ulaanbaatar Asia/Ulan_Bator Asia/Urumqi Asia/Ust-Nera Asia/Vientiane Asia/Vladivostok Asia/Yakutsk Asia/Yekaterinburg Asia/Yerevan Atlantic/Azores Atlantic/Bermuda Atlantic/Canary Atlantic/Cape_Verde Atlantic/Faeroe Atlantic/Faroe Atlantic/Jan_Mayen Atlantic/Madeira Atlantic/Reykjavik Atlantic/South_Georgia Atlantic/St_Helena Atlantic/Stanley Australia/ACT Australia/Adelaide Australia/Brisbane Australia/Broken_Hill Australia/Canberra Australia/Currie Australia/Darwin Australia/Eucla Australia/Hobart Australia/LHI Australia/Lindeman Australia/Lord_Howe Australia/Melbourne Australia/NSW Australia/North Australia/Perth Australia/Queensland Australia/South Australia/Sydney Australia/Tasmania Australia/Victoria Australia/West Australia/Yancowinna Brazil/Acre Brazil/DeNoronha Brazil/East Brazil/West CET CST6CDT Canada/Atlantic Canada/Central Canada/East-Saskatchewan Canada/Eastern Canada/Mountain Canada/Newfoundland Canada/Pacific Canada/Saskatchewan Canada/Yukon Chile/Continental Chile/EasterIsland Cuba EET EST EST5EDT Egypt Eire Etc/GMT Etc/GMT+0 Etc/GMT+1 Etc/GMT+10 Etc/GMT+11 Etc/GMT+12 Etc/GMT+2 Etc/GMT+3 Etc/GMT+4 Etc/GMT+5 Etc/GMT+6 Etc/GMT+7 Etc/GMT+8 Etc/GMT+9 Etc/GMT-0 Etc/GMT-1 Etc/GMT-10 Etc/GMT-11 Etc/GMT-12 Etc/GMT-13 Etc/GMT-14 Etc/GMT-2 Etc/GMT-3 Etc/GMT-4 Etc/GMT-5 Etc/GMT-6 Etc/GMT-7 Etc/GMT-8 Etc/GMT-9 Etc/GMT0 Etc/Greenwich Etc/UCT Etc/UTC Etc/Universal Etc/Zulu Europe/Amsterdam Europe/Andorra Europe/Athens Europe/Belfast Europe/Belgrade Europe/Berlin Europe/Bratislava Europe/Brussels Europe/Bucharest Europe/Budapest Europe/Busingen Europe/Chisinau Europe/Copenhagen Europe/Dublin Europe/Gibraltar Europe/Guernsey Europe/Helsinki Europe/Isle_of_Man Europe/Istanbul Europe/Jersey Europe/Kaliningrad Europe/Kiev Europe/Lisbon Europe/Ljubljana Europe/London Europe/Luxembourg Europe/Madrid Europe/Malta Europe/Mariehamn Europe/Minsk Europe/Monaco Europe/Moscow Europe/Nicosia Europe/Oslo Europe/Paris Europe/Podgorica Europe/Prague Europe/Riga Europe/Rome Europe/Samara Europe/San_Marino Europe/Sarajevo Europe/Simferopol Europe/Skopje Europe/Sofia Europe/Stockholm Europe/Tallinn Europe/Tirane Europe/Tiraspol Europe/Uzhgorod Europe/Vaduz Europe/Vatican Europe/Vienna Europe/Vilnius Europe/Volgograd Europe/Warsaw Europe/Zagreb Europe/Zaporozhye Europe/Zurich GB GB-Eire GMT GMT+0 GMT-0 GMT0 Greenwich HST Hongkong Iceland Indian/Antananarivo Indian/Chagos Indian/Christmas Indian/Cocos Indian/Comoro Indian/Kerguelen Indian/Mahe Indian/Maldives Indian/Mauritius Indian/Mayotte Indian/Reunion Iran Israel Jamaica Japan Kwajalein Libya MET MST MST7MDT Mexico/BajaNorte Mexico/BajaSur Mexico/General #Mideast/Riyadh87 #Mideast/Riyadh88 #Mideast/Riyadh89 NZ NZ-CHAT Navajo PRC PST8PDT Pacific/Apia Pacific/Auckland Pacific/Chatham Pacific/Chuuk Pacific/Easter Pacific/Efate Pacific/Enderbury Pacific/Fakaofo Pacific/Fiji Pacific/Funafuti Pacific/Galapagos Pacific/Gambier Pacific/Guadalcanal Pacific/Guam Pacific/Honolulu Pacific/Johnston Pacific/Kiritimati Pacific/Kosrae Pacific/Kwajalein Pacific/Majuro Pacific/Marquesas Pacific/Midway Pacific/Nauru Pacific/Niue Pacific/Norfolk Pacific/Noumea Pacific/Pago_Pago Pacific/Palau Pacific/Pitcairn Pacific/Pohnpei Pacific/Ponape Pacific/Port_Moresby Pacific/Rarotonga Pacific/Saipan Pacific/Samoa Pacific/Tahiti Pacific/Tarawa Pacific/Tongatapu Pacific/Truk Pacific/Wake Pacific/Wallis Pacific/Yap Poland Portugal ROC ROK Singapore SystemV/AST4 SystemV/AST4ADT SystemV/CST6 SystemV/CST6CDT SystemV/EST5 SystemV/EST5EDT SystemV/HST10 SystemV/MST7 SystemV/MST7MDT SystemV/PST8 SystemV/PST8PDT SystemV/YST9 SystemV/YST9YDT Turkey UCT US/Alaska US/Aleutian US/Arizona US/Central US/East-Indiana US/Eastern US/Hawaii US/Indiana-Starke US/Michigan US/Mountain US/Pacific US/Pacific-New US/Samoa UTC Universal W-SU WET Zulu rufus-scheduler-3.1.10/rufus-scheduler.gemspec000066400000000000000000000017231262271731200214070ustar00rootroot00000000000000 Gem::Specification.new do |s| s.name = 'rufus-scheduler' s.version = File.read( File.expand_path('../lib/rufus/scheduler.rb', __FILE__) ).match(/ VERSION *= *['"]([^'"]+)/)[1] s.platform = Gem::Platform::RUBY s.authors = [ 'John Mettraux' ] s.email = [ 'jmettraux@gmail.com' ] s.homepage = 'http://github.com/jmettraux/rufus-scheduler' s.rubyforge_project = 'rufus' s.license = 'MIT' s.summary = 'job scheduler for Ruby (at, cron, in and every jobs)' s.description = %{ job scheduler for Ruby (at, cron, in and every jobs). }.strip #s.files = `git ls-files`.split("\n") s.files = Dir[ 'Rakefile', 'lib/**/*.rb', #'spec/**/*.rb', 'test/**/*.rb', '*.gemspec', '*.txt', '*.rdoc', '*.md' ] #s.add_runtime_dependency 'tzinfo' s.add_development_dependency 'rake' s.add_development_dependency 'rspec', '>= 2.13.0' s.add_development_dependency 'chronic' s.add_development_dependency 'tzinfo' s.require_path = 'lib' end rufus-scheduler-3.1.10/spec/000077500000000000000000000000001262271731200156515ustar00rootroot00000000000000rufus-scheduler-3.1.10/spec/basics_spec.rb000066400000000000000000000020601262271731200204520ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Sun Jun 1 05:52:24 JST 2014 # require 'spec_helper' describe 'basics' do def tts(time) time.strftime('%Y-%m-%d %H:%M:%S %z') + (time.dst? ? ' dst' : '') end describe 'Time.new' do it 'accepts a timezone final argument' do if jruby? or ruby18? expect(true).to be(true) else expect( tts(Time.new(2014, 1, 1, 1, 0, 0, '+01:00')) ).to eq('2014-01-01 01:00:00 +0100') expect( tts(Time.new(2014, 8, 1, 1, 0, 0, '+01:00')) ).to eq('2014-08-01 01:00:00 +0100') expect( tts(Time.new(2014, 8, 1, 1, 0, 0, '+01:00')) ).to eq('2014-08-01 01:00:00 +0100') end end end describe 'Time.local' do it 'works as expected' do expect( tts(in_zone('Europe/Berlin') { Time.local(2014, 1, 1, 1, 0, 0) }) ).to eq('2014-01-01 01:00:00 +0100') expect( tts(in_zone('Europe/Berlin') { Time.local(2014, 8, 1, 1, 0, 0) }) ).to eq('2014-08-01 01:00:00 +0200 dst') end end end rufus-scheduler-3.1.10/spec/cronline_spec.rb000066400000000000000000001010571262271731200210250ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Sat Mar 21 12:55:27 JST 2009 # require 'spec_helper' class Time def to_compact_s off = self.utc_offset / 3600 off = off >= 0 ? "+#{off}" : off.to_s self.strftime('%H%M') + off + self.dup.utc.strftime('(%H%M)') end end describe Rufus::Scheduler::CronLine do def cl(cronline_string) Rufus::Scheduler::CronLine.new(cronline_string) end def nt(cronline, now) Rufus::Scheduler::CronLine.new(cronline).next_time(now) end def ntz(cronline, now) tz = cronline.split.last tu = nt(cronline, now).utc in_zone(tz) { tu.getlocal } end def pt(cronline, now) Rufus::Scheduler::CronLine.new(cronline).previous_time(now) end def ptz(cronline, now) tz = cronline.split.last tu = pt(cronline, now).utc in_zone(tz) { tu.getlocal } end def ns(cronline, now) Rufus::Scheduler::CronLine.new(cronline).next_second(now) end def ps(cronline, now) Rufus::Scheduler::CronLine.new(cronline).prev_second(now) end def match(line, time) expect(cl(line).matches?(time)).to eq(true) end def no_match(line, time) expect(cl(line).matches?(time)).to eq(false) end def to_a(line, array) expect(cl(line).to_array).to eq(array) end describe '.new' do it 'interprets cron strings correctly' do to_a '* * * * *', [ [0], nil, nil, nil, nil, nil, nil, nil ] to_a '10-12 * * * *', [ [0], [10, 11, 12], nil, nil, nil, nil, nil, nil ] to_a '* * * * sun,mon', [ [0], nil, nil, nil, nil, [0, 1], nil, nil ] to_a '* * * * mon-wed', [ [0], nil, nil, nil, nil, [1, 2, 3], nil, nil ] to_a '* * * * 7', [ [0], nil, nil, nil, nil, [0], nil, nil ] to_a '* * * * 0', [ [0], nil, nil, nil, nil, [0], nil, nil ] to_a '* * * * 0,1', [ [0], nil, nil, nil, nil, [0,1], nil, nil ] to_a '* * * * 7,1', [ [0], nil, nil, nil, nil, [0,1], nil, nil ] to_a '* * * * 7,0', [ [0], nil, nil, nil, nil, [0], nil, nil ] to_a '* * * * sun,2-4', [ [0], nil, nil, nil, nil, [0, 2, 3, 4], nil, nil ] to_a '* * * * sun,mon-tue', [ [0], nil, nil, nil, nil, [0, 1, 2], nil, nil ] to_a '* * * * * *', [ nil, nil, nil, nil, nil, nil, nil, nil ] to_a '1 * * * * *', [ [1], nil, nil, nil, nil, nil, nil, nil ] to_a '7 10-12 * * * *', [ [7], [10, 11, 12], nil, nil, nil, nil, nil, nil ] to_a '1-5 * * * * *', [ [1,2,3,4,5], nil, nil, nil, nil, nil, nil, nil ] to_a '0 0 1 1 *', [ [0], [0], [0], [1], [1], nil, nil, nil ] to_a '52 0 * * *', [ [0], [52], [0], nil, nil, nil, nil, nil ] #if ruby18? # to_a '0 23-24 * * *', [ [0], [0], [0, 23], nil, nil, nil, nil, nil ] #else # to_a '0 23-24 * * *', [ [0], [0], [23, 0], nil, nil, nil, nil, nil ] #end # # as reported by Aimee Rose in # https://github.com/jmettraux/rufus-scheduler/issues/56 to_a '0 23-24 * * *', [ [0], [0], [0, 23], nil, nil, nil, nil, nil ] #if ruby18? # to_a '0 23-2 * * *', [ [0], [0], [0, 1, 2, 23], nil, nil, nil, nil, nil ] #else # to_a '0 23-2 * * *', [ [0], [0], [23, 0, 1, 2], nil, nil, nil, nil, nil ] #end to_a '0 23-2 * * *', [ [0], [0], [0, 1, 2, 23], nil, nil, nil, nil, nil ] # modulo forms work for five-field forms to_a '*/17 * * * *', [[0], [0, 17, 34, 51], nil, nil, nil, nil, nil, nil] to_a '13 */17 * * *', [[0], [13], [0, 17], nil, nil, nil, nil, nil] # modulo forms work for six-field forms to_a '*/17 * * * * *', [[0, 17, 34, 51], nil, nil, nil, nil, nil, nil, nil] to_a '13 */17 * * * *', [[13], [0, 17, 34, 51], nil, nil, nil, nil, nil, nil] end it 'rejects invalid weekday expressions' do expect { cl '0 17 * * MON_FRI' }.to raise_error(ArgumentError) # underline instead of dash expect { cl '* * * * 9' }.to raise_error(ArgumentError) expect { cl '* * * * 0-12' }.to raise_error(ArgumentError) expect { cl '* * * * BLABLA' }.to raise_error(ArgumentError) end it 'rejects invalid cronlines' do expect { cl '* nada * * 9' }.to raise_error(ArgumentError) end it 'interprets cron strings with TZ correctly' do to_a('* * * * * EST', [ [0], nil, nil, nil, nil, nil, nil, 'EST' ]) to_a('* * * * * * EST', [ nil, nil, nil, nil, nil, nil, nil, 'EST' ]) to_a( '* * * * * * America/Chicago', [ nil, nil, nil, nil, nil, nil, nil, 'America/Chicago' ]) to_a( '* * * * * * America/New_York', [ nil, nil, nil, nil, nil, nil, nil, 'America/New_York' ]) expect { cl '* * * * * NotATimeZone' }.to raise_error(ArgumentError) expect { cl '* * * * * * NotATimeZone' }.to raise_error(ArgumentError) end it 'interprets cron strings with / (slashes) correctly' do to_a( '0 */2 * * *', [ [0], [0], (0..23).select { |e| e.even? }, nil, nil, nil, nil, nil ]) to_a( '0 0-23/2 * * *', [ [0], [0], (0..23).select { |e| e.even? }, nil, nil, nil, nil, nil ]) to_a( '0 7-23/2 * * *', [ [0], [0], (7..23).select { |e| e.odd? }, nil, nil, nil, nil, nil ]) to_a( '*/10 * * * *', [ [0], [0, 10, 20, 30, 40, 50], nil, nil, nil, nil, nil, nil ]) # fighting https://github.com/jmettraux/rufus-scheduler/issues/65 # to_a( '*/10 * * * * Europe/Berlin', [ [0], [ 0, 10, 20, 30, 40, 50], nil, nil, nil, nil, nil, 'Europe/Berlin' ]) end it 'accepts lonely / (slashes) (like <= 2.0.19 did)' do # fighting https://github.com/jmettraux/rufus-scheduler/issues/65 to_a( '/10 * * * *', [ [0], [ 0, 10, 20, 30, 40, 50], nil, nil, nil, nil, nil, nil ]) end it 'rejects / for days (every other wednesday)' do expect { Rufus::Scheduler::CronLine.new('* * * * wed/2') }.to raise_error(ArgumentError) end it 'does not support ranges for monthdays (sun#1-sun#2)' do expect { Rufus::Scheduler::CronLine.new('* * * * sun#1-sun#2') }.to raise_error(ArgumentError) end it 'accepts items with initial 0' do to_a( '09 * * * *', [ [0], [9], nil, nil, nil, nil, nil, nil ]) to_a( '09-12 * * * *', [ [0], [9, 10, 11, 12], nil, nil, nil, nil, nil, nil ]) to_a( '07-08 * * * *', [ [0], [7, 8], nil, nil, nil, nil, nil, nil ]) to_a( '* */08 * * *', [ [0], nil, [0, 8, 16], nil, nil, nil, nil, nil ]) to_a( '* */07 * * *', [ [0], nil, [0, 7, 14, 21], nil, nil, nil, nil, nil ]) to_a( '* 01-09/04 * * *', [ [0], nil, [1, 5, 9], nil, nil, nil, nil, nil ]) to_a( '* * * * 06', [ [0], nil, nil, nil, nil, [6], nil, nil ]) end it 'interprets cron strings with L correctly' do to_a( '* * L * *', [[0], nil, nil, ['L'], nil, nil, nil, nil ]) to_a( '* * 2-5,L * *', [[0], nil, nil, [2,3,4,5,'L'], nil, nil, nil, nil ]) to_a( '* * */8,L * *', [[0], nil, nil, [1,9,17,25,'L'], nil, nil, nil, nil ]) end it 'does not support ranges for L' do expect { cl '* * 15-L * *'}.to raise_error(ArgumentError) expect { cl '* * L/4 * *'}.to raise_error(ArgumentError) end it 'does not support multiple Ls' do expect { cl '* * L,L * *'}.to raise_error(ArgumentError) end it 'raises if L is used for something else than days' do expect { cl '* L * * *'}.to raise_error(ArgumentError) end it 'raises for out of range input' do expect { cl '60-62 * * * *'}.to raise_error(ArgumentError) expect { cl '62 * * * *'}.to raise_error(ArgumentError) expect { cl '60 * * * *'}.to raise_error(ArgumentError) expect { cl '* 25-26 * * *'}.to raise_error(ArgumentError) expect { cl '* 25 * * *'}.to raise_error(ArgumentError) # # as reported by Aimee Rose in # https://github.com/jmettraux/rufus-scheduler/pull/58 end it 'sorts seconds' do to_a( '23,30,10 * * * * *', [ [10,23,30], nil, nil, nil, nil, nil, nil, nil ]) end it 'sorts minutes' do to_a( '23,30,10 * * * * ', [ [0], [10,23,30], nil, nil, nil, nil, nil, nil ]) end it 'sorts days' do to_a( '* * 14,7 * * ', [ [0], nil, nil, [7, 14], nil, nil, nil, nil ]) end it 'sorts months' do to_a( '* * * 11,3,4 * ', [ [0], nil, nil, nil, [3,4,11], nil, nil, nil ]) end it 'sorts days of week' do to_a( '* * * * Sun,Fri,2 ', [ [0], nil, nil, nil, nil, [0, 2, 5], nil, nil ]) end end describe '#next_time' do it 'computes the next occurence correctly' do in_zone 'Europe/Berlin' do now = Time.at(0) - 3600 expect(nt('* * * * *', now)).to eq(now + 60) expect(nt('* * * * sun', now)).to eq(now + 259200) expect(nt('* * * * * *', now)).to eq(now + 1) expect(nt('* * 13 * fri', now)).to eq(now + 3715200) expect(nt('10 12 13 12 *', now)).to eq(now + 29938200) # this one is slow (1 year == 3 seconds) # # historical note: # (comment made in 2006 or 2007, the underlying libs got better and # that slowness is gone) expect(nt('0 0 * * thu', now)).to eq(now + 604800) expect(nt('00 0 * * thu', now)).to eq(now + 604800) expect(nt('0 0 * * *', now)).to eq(now + 24 * 3600) expect(nt('0 24 * * *', now)).to eq(now + 24 * 3600) now = local(2008, 12, 31, 23, 59, 59, 0) expect(nt('* * * * *', now)).to eq(now + 1) end end it 'computes the next occurence correctly in local TZ (TZ not specified)' do now = local(1970, 1, 1) expect(nt('* * * * *', now)).to eq(local(1970, 1, 1, 0, 1)) expect(nt('* * * * sun', now)).to eq(local(1970, 1, 4)) expect(nt('* * * * * *', now)).to eq(local(1970, 1, 1, 0, 0, 1)) expect(nt('* * 13 * fri', now)).to eq(local(1970, 2, 13)) expect(nt('10 12 13 12 *', now)).to eq(local(1970, 12, 13, 12, 10)) # this one is slow (1 year == 3 seconds) expect(nt('* * 1 6 *', now)).to eq(local(1970, 6, 1)) expect(nt('0 0 * * thu', now)).to eq(local(1970, 1, 8)) end it 'computes the next occurence correctly in UTC (TZ specified)' do zone = 'Europe/Stockholm' now = in_zone(zone) { Time.local(1970, 1, 1) } expect(nt("* * * * * #{zone}", now)).to eq(utc(1969, 12, 31, 23, 1)) expect(nt("* * * * sun #{zone}", now)).to eq(utc(1970, 1, 3, 23)) expect(nt("* * * * * * #{zone}", now)).to eq(utc(1969, 12, 31, 23, 0, 1)) expect(nt("* * 13 * fri #{zone}", now)).to eq(utc(1970, 2, 12, 23)) expect(nt("10 12 13 12 * #{zone}", now)).to eq(utc(1970, 12, 13, 11, 10)) expect(nt("* * 1 6 * #{zone}", now)).to eq(utc(1970, 5, 31, 23)) expect(nt("0 0 * * thu #{zone}", now)).to eq(utc(1970, 1, 7, 23)) end it 'computes the next time correctly when there is a sun#2 involved' do expect(nt('* * * * sun#1', local(1970, 1, 1))).to eq(local(1970, 1, 4)) expect(nt('* * * * sun#2', local(1970, 1, 1))).to eq(local(1970, 1, 11)) expect(nt('* * * * sun#2', local(1970, 1, 12))).to eq(local(1970, 2, 8)) end it 'computes next time correctly when there is a sun#2,sun#3 involved' do expect( nt('* * * * sun#2,sun#3', local(1970, 1, 1))).to eq(local(1970, 1, 11)) expect( nt('* * * * sun#2,sun#3', local(1970, 1, 12))).to eq(local(1970, 1, 18)) end it 'understands sun#L' do expect(nt('* * * * sun#L', local(1970, 1, 1))).to eq(local(1970, 1, 25)) end it 'understands sun#-1' do expect(nt('* * * * sun#-1', local(1970, 1, 1))).to eq(local(1970, 1, 25)) end it 'understands sun#-2' do expect(nt('* * * * sun#-2', local(1970, 1, 1))).to eq(local(1970, 1, 18)) end it 'computes the next time correctly when "L" (last day of month)' do expect(nt('* * L * *', lo(1970, 1, 1))).to eq(lo(1970, 1, 31)) expect(nt('* * L * *', lo(1970, 2, 1))).to eq(lo(1970, 2, 28)) expect(nt('* * L * *', lo(1972, 2, 1))).to eq(lo(1972, 2, 29)) expect(nt('* * L * *', lo(1970, 4, 1))).to eq(lo(1970, 4, 30)) end it 'returns a time with subseconds chopped off' do expect( nt('* * * * *', Time.now).usec).to eq(0) expect( nt('* * * * *', Time.now).iso8601(10).match(/\.0+[^\d]/)).not_to eq(nil) end # New York EST: UTC-5 # summer (dst) EDT: UTC-4 # gh-127 # it 'survives TZInfo::AmbiguousTime' do if ruby18? or jruby? expect( ntz( '30 1 31 10 * America/New_York', ltz('America/New_York', 2004, 10, 1) ).strftime('%Y-%m-%d %H:%M:%S') ).to eq('2004-10-31 01:30:00') else expect( ntz( '30 1 31 10 * America/New_York', ltz('America/New_York', 2004, 10, 1) ) ).to eq( ltz('America/New_York', 0, 30, 1, 31, 10, 2004, nil, nil, true, nil) # EDT summer time UTC-4 ) end end # gh-127 # it 'survives TZInfo::PeriodNotFound' do expect( ntz( '0 2 9 3 * America/New_York', ltz('America/New_York', 2014, 3, 1) ) ).to eq(ltz('America/New_York', 2015, 3, 9, 2, 0, 0)) end it 'understands six-field crontabs' do expect(nt('* * * * * *',local(1970,1,1,1,1,1))).to( eq(local(1970,1,1,1,1,2)) ) expect(nt('* * * * * *',local(1970,1,1,1,1,2))).to( eq(local(1970,1,1,1,1,3)) ) expect(nt('*/10 * * * * *',local(1970,1,1,1,1,0))).to( eq(local(1970,1,1,1,1,10)) ) expect(nt('*/10 * * * * *',local(1970,1,1,1,1,9))).to( eq(local(1970,1,1,1,1,10)) ) expect(nt('*/10 * * * * *',local(1970,1,1,1,1,10))).to( eq(local(1970,1,1,1,1,20)) ) expect(nt('*/10 * * * * *',local(1970,1,1,1,1,40))).to( eq(local(1970,1,1,1,1,50)) ) expect(nt('*/10 * * * * *',local(1970,1,1,1,1,49))).to( eq(local(1970,1,1,1,1,50)) ) expect(nt('*/10 * * * * *',local(1970,1,1,1,1,50))).to( eq(local(1970,1,1,1,2,00)) ) end end describe '#next_second' do [ [ '*/10 * * * * *', local(1970,1,1,1,1, 0), 0 ], # 0 sec to 0s mark [ '*/10 * * * * *', local(1970,1,1,1,1, 1), 9 ], # 9 sec to 10s mark [ '*/10 * * * * *', local(1970,1,1,1,1, 9), 1 ], # 1 sec to 10s mark [ '*/10 * * * * *', local(1970,1,1,1,1,10), 0 ], # 0 sec to 10s mark [ '*/10 * * * * *', local(1970,1,1,1,1,11), 9 ], # 9 sec to 20s mark [ '*/10 * * * * *', local(1970,1,1,1,1,19), 1 ], # 1 sec to 20s mark [ '*/10 * * * * *', local(1970,1,1,1,1,20), 0 ], # 0 sec to 20s mark [ '*/10 * * * * *', local(1970,1,1,1,1,21), 9 ], # 1 sec to 30s mark # ... [ '*/10 * * * * *', local(1970,1,1,1,1,49), 1 ], # 9 sec to 50s mark [ '*/10 * * * * *', local(1970,1,1,1,1,50), 0 ], # 0 sec to 50s mark [ '*/10 * * * * *', local(1970,1,1,1,1,51), 9 ], ].each do |cronline, now, sec| it "ensures that next_second('#{cronline}', #{now}) is #{sec}" do expect(ns(cronline,now)).to eq(sec) end end end describe '#prev_second' do it 'returns the time to the closest previous second' do t = local(1970, 1, 1, 1, 1, 42) expect(ps('35,44 * * * * *', t)).to eq(7) end context 'when time sec is lower then all cron seconds (gh-177)' do it 'returns the time to the last second a minute before' do t = local(1970, 1, 1, 1, 1, 42) expect(ps('43,44 * * * * *', t)).to eq(58) end end end describe '#previous_time' do it 'returns the previous time the cron should have triggered' do expect( pt('* * * * sun', lo(1970, 1, 1))).to eq(lo(1969, 12, 28, 23, 59, 00)) expect( pt('* * 13 * *', lo(1970, 1, 1))).to eq(lo(1969, 12, 13, 23, 59, 00)) expect( pt('0 12 13 * *', lo(1970, 1, 1))).to eq(lo(1969, 12, 13, 12, 00)) expect( pt('0 0 2 1 *', lo(1970, 1, 1))).to eq(lo(1969, 1, 2, 0, 00)) expect( pt('* * * * * sun', lo(1970, 1, 1))).to eq(lo(1969, 12, 28, 23, 59, 59)) end it 'jumps to the previous minute if necessary (gh-177)' do t = local(1970, 12, 31, 1, 1, 0) # vanilla expect(pt('43,44 * * * * *', t)).to eq(lo(1970, 12, 31, 1, 0, 44)) t = local(1970, 12, 31, 1, 1, 30) # 30 < 43 <---- here! expect(pt('43,44 * * * * *', t)).to eq(lo(1970, 12, 31, 1, 0, 44)) t = local(1970, 12, 31, 1, 1, 43) # 43 <= 43 < 44 expect(pt('43,44 * * * * *', t)).to eq(lo(1970, 12, 31, 1, 0, 44)) t = local(1970, 12, 31, 1, 1, 44) # 44 <= 44 expect(pt('43,44 * * * * *', t)).to eq(lo(1970, 12, 31, 1, 1, 43)) t = local(1970, 12, 31, 1, 1, 59) # 44 < 59 expect(pt('43,44 * * * * *', t)).to eq(lo(1970, 12, 31, 1, 1, 44)) t = local(1970, 12, 31, 1, 1, 30) # a bigger jump expect(pt('43,44 10 * * * *', t)).to eq(lo(1970, 12, 31, 0, 10, 44)) end # New York EST: UTC-5 # summer (dst) EDT: UTC-4 # gh-127 # it 'survives TZInfo::AmbiguousTime' do if ruby18? or jruby? expect( ptz( '30 1 31 10 * America/New_York', ltz('America/New_York', 2004, 10, 31, 14, 30, 0) ).strftime('%Y-%m-%d %H:%M:%S') ).to eq('2004-10-31 01:30:00') else expect( ptz( '30 1 31 10 * America/New_York', ltz('America/New_York', 2004, 10, 31, 14, 30, 0) ) ).to eq( ltz('America/New_York', 0, 30, 1, 31, 10, 2004, nil, nil, false, nil) # EST time UTC-5 ) end end # gh-127 # it 'survives TZInfo::PeriodNotFound' do expect( ptz( '0 2 9 3 * America/New_York', ltz('America/New_York', 2015, 3, 9, 12, 0, 0) ) ).to eq(ltz('America/New_York', 2015, 3, 9, 2, 0, 0)) end it 'computes correctly when * 0,10,20' do expect( pt('* 0,10,20 * * *', lo(2000, 1, 1))).to eq( lo(1999, 12, 31, 20, 59, 00)) end it 'computes correctly when * */10' do expect( pt('* */10 * * *', lo(2000, 1, 1))).to eq( lo(1999, 12, 31, 20, 59, 00)) end end describe '#matches?' do # it 'matches correctly in UTC (TZ not specified)' do # # match '* * * * *', utc(1970, 1, 1, 0, 1) # match '* * * * sun', utc(1970, 1, 4) # match '* * * * * *', utc(1970, 1, 1, 0, 0, 1) # match '* * 13 * fri', utc(1970, 2, 13) # # match '10 12 13 12 *', utc(1970, 12, 13, 12, 10) # match '* * 1 6 *', utc(1970, 6, 1) # # match '0 0 * * thu', utc(1970, 1, 8) # # match '0 0 1 1 *', utc(2012, 1, 1) # no_match '0 0 1 1 *', utc(2012, 1, 1, 1, 0) # end it 'matches correctly in local TZ (TZ not specified)' do match '* * * * *', local(1970, 1, 1, 0, 1) match '* * * * sun', local(1970, 1, 4) match '* * * * * *', local(1970, 1, 1, 0, 0, 1) match '* * 13 * fri', local(1970, 2, 13) match '10 12 13 12 *', local(1970, 12, 13, 12, 10) match '* * 1 6 *', local(1970, 6, 1) match '0 0 * * thu', local(1970, 1, 8) match '0 0 1 1 *', local(2012, 1, 1) no_match '0 0 1 1 *', local(2012, 1, 1, 1, 0) end it 'matches correctly in UTC (TZ specified)' do zone = 'Europe/Stockholm' match "* * * * * #{zone}", utc(1969, 12, 31, 23, 1) match "* * * * sun #{zone}", utc(1970, 1, 3, 23) match "* * * * * * #{zone}", utc(1969, 12, 31, 23, 0, 1) match "* * 13 * fri #{zone}", utc(1970, 2, 12, 23) match "10 12 13 12 * #{zone}", utc(1970, 12, 13, 11, 10) match "* * 1 6 * #{zone}", utc(1970, 5, 31, 23) match "0 0 * * thu #{zone}", utc(1970, 1, 7, 23) end it 'matches correctly when there is a sun#2 involved' do match '* * 13 * fri#2', utc(1970, 2, 13) no_match '* * 13 * fri#2', utc(1970, 2, 20) end it 'matches correctly when there is a L involved' do match '* * L * *', utc(1970, 1, 31) no_match '* * L * *', utc(1970, 1, 30) end it 'matches correctly when there is a sun#2,sun#3 involved' do no_match '* * * * sun#2,sun#3', local(1970, 1, 4) match '* * * * sun#2,sun#3', local(1970, 1, 11) match '* * * * sun#2,sun#3', local(1970, 1, 18) no_match '* * * * sun#2,sun#3', local(1970, 1, 25) end it 'matches correctly for seconds' do match '* * * * * *', local(1970, 1, 11) match '* * * * * *', local(1970, 1, 11, 0, 0, 13) end it 'matches correctly for seconds / interval' do match '*/2 * * * * *', local(1970, 1, 11) match '*/5 * * * * *', local(1970, 1, 11) match '*/5 * * * * *', local(1970, 1, 11, 0, 0, 0) no_match '*/5 * * * * *', local(1970, 1, 11, 0, 0, 1) match '*/5 * * * * *', local(1970, 1, 11, 0, 0, 5) match '*/2 * * * * *', local(1970, 1, 11, 0, 0, 2) match '*/2 * * * * *', local(1970, 1, 11, 0, 0, 2, 500) end end describe '#monthdays' do it 'returns the appropriate "sun#2"-like string' do class Rufus::Scheduler::CronLine public :monthdays end cl = Rufus::Scheduler::CronLine.new('* * * * *') expect(cl.monthdays(local(1970, 1, 1))).to eq(%w[ thu#1 thu#-5 ]) expect(cl.monthdays(local(1970, 1, 7))).to eq(%w[ wed#1 wed#-4 ]) expect(cl.monthdays(local(1970, 1, 14))).to eq(%w[ wed#2 wed#-3 ]) expect(cl.monthdays(local(2011, 3, 11))).to eq(%w[ fri#2 fri#-3 ]) end end describe '#frequency' do it 'returns the shortest delta between two occurrences' do expect(Rufus::Scheduler::CronLine.new( '* * * * *').frequency).to eq(60) expect(Rufus::Scheduler::CronLine.new( '* * * * * *').frequency).to eq(1) expect(Rufus::Scheduler::CronLine.new( '5 23 * * *').frequency).to eq(24 * 3600) expect(Rufus::Scheduler::CronLine.new( '5 * * * *').frequency).to eq(3600) expect(Rufus::Scheduler::CronLine.new( '10,20,30 * * * *').frequency).to eq(600) expect(Rufus::Scheduler::CronLine.new( '10,20,30 * * * * *').frequency).to eq(10) end it 'spots B-A vs C-B asymmetry in five-field forms' do expect(Rufus::Scheduler::CronLine.new( '10,17,30 * * * *').frequency).to eq(7 * 60) expect(Rufus::Scheduler::CronLine.new( '10,23,30 * * * *').frequency).to eq(7 * 60) expect(Rufus::Scheduler::CronLine.new( '23,10,30 * * * *').frequency).to eq(7 * 60) end it 'spots B-A vs C-B asymmetry in six-field forms' do expect(Rufus::Scheduler::CronLine.new( '10,17,30 * * * * *').frequency).to eq(7) expect(Rufus::Scheduler::CronLine.new( '10,23,30 * * * * *').frequency).to eq(7) expect(Rufus::Scheduler::CronLine.new( '23,10,30 * * * * *').frequency).to eq(7) end it 'handles crontab steps syntax in five-field forms' do expect(Rufus::Scheduler::CronLine.new( '*/10 * * * *').frequency).to eq(10 * 60) expect(Rufus::Scheduler::CronLine.new( '* */10 * * *').frequency).to eq(60) # "*" all minutes [0..59] expect(Rufus::Scheduler::CronLine.new( '0 */10 * * *').frequency).to eq(4 * 60 * 60) # 2000 to 0000 end it 'handles crontab steps syntax in six-field forms' do expect(Rufus::Scheduler::CronLine.new( '*/10 * * * * *').frequency).to eq(10) expect(Rufus::Scheduler::CronLine.new( '* */10 * * * *').frequency).to eq(1) # "*" all seconds [0..59] expect(Rufus::Scheduler::CronLine.new( '0 */10 * * * *').frequency).to eq(10 * 60) end end describe '#brute_frequency' do it 'returns the shortest delta between two occurrences' do expect(Rufus::Scheduler::CronLine.new( '* * * * *').brute_frequency).to eq(60) expect(Rufus::Scheduler::CronLine.new( '* * * * * *').brute_frequency).to eq(1) expect(Rufus::Scheduler::CronLine.new( '5 23 * * *').brute_frequency).to eq(24 * 3600) expect(Rufus::Scheduler::CronLine.new( '5 * * * *').brute_frequency).to eq(3600) expect(Rufus::Scheduler::CronLine.new( '10,20,30 * * * *').brute_frequency).to eq(600) #Rufus::Scheduler::CronLine.new( # '10,20,30 * * * * *').brute_frequency.should == 10 # # takes > 20s ... end # some combos only appear every other year... # it 'does not go into an infinite loop' do expect(Rufus::Scheduler::CronLine.new( '1 2 3 4 5').brute_frequency).to eq(31622400) end it 'spots B-A vs C-B asymmetry in five-field forms' do expect(Rufus::Scheduler::CronLine.new( '10,17,30 * * * *').brute_frequency).to eq(7 * 60) expect(Rufus::Scheduler::CronLine.new( '10,23,30 * * * *').brute_frequency).to eq(7 * 60) end it 'spots B-A vs C-B asymmetry in six-field forms' do expect(Rufus::Scheduler::CronLine.new( '10,17,30 * * * * *').brute_frequency).to eq(7) expect(Rufus::Scheduler::CronLine.new( '10,23,30 * * * * *').brute_frequency).to eq(7) end it 'handles crontab modulo syntax in five-field forms' do expect(Rufus::Scheduler::CronLine.new( '*/10 * * * *').brute_frequency).to eq(10 * 60) expect(Rufus::Scheduler::CronLine.new( '* */10 * * *').brute_frequency).to eq(60) # "*" all minutes [0..59] expect(Rufus::Scheduler::CronLine.new( '0 */10 * * *').brute_frequency).to eq(4 * 60 * 60) # 2000 to 0000 end it 'handles crontab modulo syntax in six-field forms' do expect(Rufus::Scheduler::CronLine.new( '*/10 * * * * *').brute_frequency).to eq(10) expect(Rufus::Scheduler::CronLine.new( '* */10 * * * *').brute_frequency).to eq(1) # "*" all seconds [0..59] expect(Rufus::Scheduler::CronLine.new( '0 */10 * * * *').brute_frequency).to eq(10 * 60) end end context 'summer time' do # let's assume summer time jumps always occur on sundays # cf gh-114 # it 'schedules correctly through a switch into summer time' do in_zone 'Europe/Berlin' do # find the summer jump j = Time.parse('2014-02-28 12:00') loop do jj = j + 24 * 3600 break if jj.isdst j = jj end # test friday = j - 24 * 3600 # one day before # verify the playground... # expect(friday.isdst).to eq(false) expect((friday + 24 * 3600 * 3).isdst).to eq(true) cl0 = Rufus::Scheduler::CronLine.new('02 00 * * 1,2,3,4,5') cl1 = Rufus::Scheduler::CronLine.new('45 08 * * 1,2,3,4,5') n0 = cl0.next_time(friday) n1 = cl1.next_time(friday) expect(n0.strftime('%H:%M:%S %^a')).to eq('00:02:00 TUE') expect(n1.strftime('%H:%M:%S %^a')).to eq('08:45:00 MON') expect(n0.isdst).to eq(true) expect(n1.isdst).to eq(true) expect( (n0 - 24 * 3600 * 3).strftime('%H:%M:%S %^a')).to eq('23:02:00 FRI') expect( (n1 - 24 * 3600 * 3).strftime('%H:%M:%S %^a')).to eq('07:45:00 FRI') end end it 'schedules correctly through a switch out of summer time' do in_zone 'Europe/Berlin' do # find the winter jump j = Time.parse('2014-08-31 12:00') loop do jj = j + 24 * 3600 break if jj.isdst == false j = jj end # test friday = j - 24 * 3600 # one day before # verify the playground... # expect(friday.isdst).to eq(true) expect((friday + 24 * 3600 * 3).isdst).to eq(false) cl0 = Rufus::Scheduler::CronLine.new('02 00 * * 1,2,3,4,5') cl1 = Rufus::Scheduler::CronLine.new('45 08 * * 1,2,3,4,5') n0 = cl0.next_time(friday) n1 = cl1.next_time(friday) expect(n0.strftime('%H:%M:%S %^a')).to eq('00:02:00 MON') expect(n1.strftime('%H:%M:%S %^a')).to eq('08:45:00 MON') expect(n0.isdst).to eq(false) expect(n1.isdst).to eq(false) expect( (n0 - 24 * 3600 * 3).strftime('%H:%M:%S %^a')).to eq('01:02:00 FRI') expect( (n1 - 24 * 3600 * 3).strftime('%H:%M:%S %^a')).to eq('09:45:00 FRI') end end it 'correctly increments through a DST transition' do expect( nt('* * * * * America/Los_Angeles', Time.utc(2015, 3, 8, 9, 59)) ).to eq(Time.utc(2015, 3, 8, 10, 00)) end it 'correctly increments every minute through a DST transition' do in_zone 'America/Los_Angeles' do line = cl('* * * * * America/Los_Angeles') t = Time.local(2015, 3, 8, 1, 57) points = 4.times.collect do t = line.next_time(t) t.to_compact_s end expect(points).to eq([ '0158-8(0958)', '0159-8(0959)', '0300-7(1000)', '0301-7(1001)' ]) end end it 'correctly decrements through a DST transition' do expect( pt('* * * * * America/Los_Angeles', Time.utc(2015, 3, 8, 10, 00)) ).to eq(Time.utc(2015, 3, 8, 9, 59)) end it 'correctly decrements every minute through a DST transition' do in_zone 'America/Los_Angeles' do line = cl('* * * * * America/Los_Angeles') t = Time.local(2015, 3, 8, 3, 2) points = 4.times.collect do t = line.previous_time(t) t.to_compact_s end expect(points).to eq([ '0301-7(1001)', '0300-7(1000)', '0159-8(0959)', '0158-8(0958)' ]) end end it 'correctly increments when entering DST' do in_zone 'America/Los_Angeles' do line = cl('*/10 * * * * America/Los_Angeles') t = Time.local(2015, 3, 8, 1, 40) t1 = t.dup points = [] while t1 - t < 1 * 3600 t1 = line.next_time(t1) points << t1.to_compact_s end expect(points).to eq(%w[ 0150-8(0950) 0300-7(1000) 0310-7(1010) 0320-7(1020) 0330-7(1030) 0340-7(1040) ]) end end end context 'fall time' do it 'correctly increments through a DST transition' do expect( nt('* * * * * America/Los_Angeles', Time.utc(2015, 11, 1, 9, 59)) ).to eq(Time.utc(2015, 11, 1, 10, 00)) end it 'correctly increments every minute through a DST transition' do in_zone 'America/Los_Angeles' do line = cl('* * * * * America/Los_Angeles') #t = Time.local(2015, 11, 1, 1, 57) # # --> 2015-11-01 01:57:00 -0800 (already PST) t = Time.local(0, 57, 1, 1, 11, 2015, nil, nil, true, nil) # # --> 2015-11-01 01:57:00 -0700 (still PDT) points = 4.times.collect do t = line.next_time(t) t.to_compact_s end expect(points).to eq([ '0158-7(0858)', '0159-7(0859)', '0100-8(0900)', '0101-8(0901)' ]) end end it 'correctly decrements through a DST transition' do expect( pt('* * * * * America/Los_Angeles', Time.utc(2015, 11, 1, 10, 00)) ).to eq(Time.utc(2015, 11, 1, 9, 59)) end it 'correctly decrements every minute through a DST transition' do in_zone 'America/Los_Angeles' do line = cl('* * * * * America/Los_Angeles') t = Time.local(0, 2, 1, 1, 11, 2015, nil, nil, true, nil) # # try to force PST # TODO: at some point, try to find out if the latest jRuby still # exhibits that behaviour, report to them if necessary points = (0..3).collect do t = line.previous_time(t) t.to_compact_s end if t.zone == 'PST' expect(points).to eq([ '0101-8(0901)', '0100-8(0900)', '0159-7(0859)', '0158-7(0858)' ]) else expect(points).to eq([ '0101-7(0801)', '0100-7(0800)', '0059-7(0759)', '0058-7(0758)' ]) end end end it 'correctly increments when leaving DST' do in_zone 'America/Los_Angeles' do line = cl('*/10 * * * * America/Los_Angeles') t = Time.local(2015, 11, 1, 0, 40) t1 = t.dup points = [] while t1 - t < 2 * 3600 t1 = line.next_time(t1) points << t1.to_compact_s end expect(points).to eq([ '0050-7(0750)', # | PDT '0100-7(0800)', # | '0110-7(0810)', # V '0120-7(0820)', '0130-7(0830)', '0140-7(0840)', '0150-7(0850)', '0100-8(0900)', # + PST '0110-8(0910)', # | '0120-8(0920)', # V '0130-8(0930)', '0140-8(0940)' ]) end end end end rufus-scheduler-3.1.10/spec/error_spec.rb000066400000000000000000000047301262271731200203450ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Fri Aug 9 07:10:18 JST 2013 # require 'spec_helper' describe Rufus::Scheduler do before :each do @taoe = Thread.abort_on_exception Thread.abort_on_exception = false @ose = $stderr $stderr = StringIO.new @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown Thread.abort_on_exception = @taoe $stderr = @ose end context 'error in block' do it 'intercepts the error and describes it on $stderr' do counter = 0 @scheduler.every('0.5s') do counter += 1 fail 'argh' end sleep 2 expect(counter).to be > 2 expect($stderr.string).to match(/argh/) end end context 'error in callable' do class MyFailingHandler attr_reader :counter def initialize @counter = 0 end def call(job, time) @counter = @counter + 1 fail 'ouch' end end it 'intercepts the error and describes it on $stderr' do mfh = MyFailingHandler.new @scheduler.every('0.5s', mfh) sleep 2 expect(mfh.counter).to be > 2 expect($stderr.string).to match(/ouch/) end end context 'Rufus::Scheduler#stderr=' do it 'lets divert error information to custom files' do @scheduler.stderr = StringIO.new @scheduler.in('0s') do fail 'miserably' end sleep 0.5 expect(@scheduler.stderr.string).to match(/intercepted an error/) expect(@scheduler.stderr.string).to match(/miserably/) end end context 'error information' do it 'contains information about the error, the job and the scheduler' do @scheduler.stderr = StringIO.new @scheduler.in('0s') do fail 'miserably' end sleep 0.5 s = @scheduler.stderr.string #puts s expect(s).to match(/ENV\['TZ'\]:/) expect(s).to match(/down\?: false/) expect(s).to match(/work_threads: 1/) expect(s).to match(/running_jobs: 1/) expect(s).to match(/uptime: \d/) end end context 'Rufus::Scheduler#on_error(&block)' do it 'intercepts all StandardError instances' do $message = nil def @scheduler.on_error(job, err) $message = "#{job.class} #{job.original} #{err.message}" rescue p $! end @scheduler.in('0s') do fail 'miserably' end sleep 0.5 expect($message).to eq('Rufus::Scheduler::InJob 0s miserably') end end end rufus-scheduler-3.1.10/spec/job_array_spec.rb000066400000000000000000000011571262271731200211640ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'spec_helper' describe Rufus::Scheduler::JobArray do class DummyJob < Struct.new(:id, :next_time); end before(:each) do @array = Rufus::Scheduler::JobArray.new end describe '#push' do it 'pushes jobs' do @array.push(DummyJob.new('a', Time.local(0))) expect(@array.to_a.collect(&:id)).to eq(%w[ a ]) end it 'pushes and remove duplicates' do j = DummyJob.new('a', Time.local(0)) @array.push(j) @array.push(j) expect(@array.to_a.collect(&:id)).to eq(%w[ a ]) end end end rufus-scheduler-3.1.10/spec/job_at_spec.rb000066400000000000000000000016761262271731200204600ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'spec_helper' describe Rufus::Scheduler::AtJob do before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end describe '#unschedule' do it 'unschedules the job' do job = @scheduler.at(Time.now + 3600, :job => true) do end job.unschedule sleep 0.4 expect(@scheduler.jobs.size).to eq(0) end end describe '#scheduled_at' do it 'returns the Time at which the job got scheduled' do job = @scheduler.schedule_at((t = Time.now) + 3600) {} expect(job.scheduled_at.to_i).to be >= t.to_i - 1 expect(job.scheduled_at.to_i).to be <= t.to_i + 1 end end describe '#time' do it 'returns the time at which the job will trigger' do t = Time.now + 3600 job = @scheduler.schedule_at t do; end expect(job.time).to eq(t) end end end rufus-scheduler-3.1.10/spec/job_cron_spec.rb000066400000000000000000000047121262271731200210070ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'spec_helper' describe Rufus::Scheduler::CronJob do before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end context 'normal' do it 'triggers near the zero second' do job = @scheduler.schedule_cron '* * * * *' do; end sleep_until_next_minute expect(job.last_time.to_i % 10).to eq(0) end end #context 'sub-minute' do # # it 'triggers near the zero second' do # # job = @scheduler.schedule_cron '* * * * * *' do; end # # sleep 1.5 # # p job.last_time # p job.last_time.to_f # end #end context 'first_at/in' do it 'does not trigger before first_at is reached' do t = Time.now job = @scheduler.schedule_cron '* * * * * *', :first_in => '3s' do triggered = Time.now end sleep 1 #p [ t, t.to_f ] #p [ job.last_time, job.last_time.to_f ] #p [ job.first_at, job.first_at.to_f ] expect(job.first_at).to be_within_1s_of(t + 3) expect(job.last_time).to eq(nil) end it 'triggers for the first time at first_at' do first_time = nil t = Time.now job = @scheduler.schedule_cron '* * * * * *', :first_in => '3s' do first_time ||= Time.now end sleep 4.5 expect(job.first_at).to be_within_1s_of(t + 3) expect(first_time).to be_within_1s_of(job.first_at) end end context 'scheduling the cron itself' do # for https://github.com/jmettraux/rufus-scheduler/issues/95 # # schedule_cron takes more than 30 seconds, blocking... # it 'does not sit scheduling and blocking...' do n = Time.now first = nil job = @scheduler.schedule_cron '*/2 * * * * *' do first ||= Time.now end expect(Time.now - n).to be < 1.0 loop do next unless first expect(first - n).to be < 4.0 break end end end describe '.next_time' do it 'returns the next trigger time' do n = Time.now nt = Time.parse("#{n.year}-#{n.month + 1}-01") expect( @scheduler.schedule_cron('* * 1 * *', lambda {}).next_time ).to eq(nt) end it 'returns the next trigger time (first_at => Time)' do ft = Time.parse('2100-12-31') job = @scheduler.schedule_cron('* * 1 * *', :first_at => ft) {} expect(job.next_time).to eq(ft) end end end rufus-scheduler-3.1.10/spec/job_every_spec.rb000066400000000000000000000040461262271731200212000ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'spec_helper' describe Rufus::Scheduler::EveryJob do before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end it 'triggers as expected' do counter = 0 @scheduler.every '1s' do counter = counter + 1 end sleep 3.5 expect([ 2, 3 ]).to include(counter) end it 'lets its @next_time change in-flight' do times = [] @scheduler.every '1s' do |job| times << Time.now job.next_time = Time.now + 3 if times.count == 2 end sleep 0.3 while times.count < 3 #p [ times[1] - times[0], times[2] - times[1] ] expect(times[1] - times[0]).to be > 1.0 expect(times[1] - times[0]).to be < 1.4 expect(times[2] - times[1]).to be > 3.0 expect(times[2] - times[1]).to be < 3.4 end context 'summer time' do it 'triggers correctly through a DST transition' do job = Rufus::Scheduler::EveryJob.new(@scheduler, '1m', {}, lambda {}) t1 = ltz('America/Los_Angeles', 2015, 3, 8, 1, 55) t2 = ltz('America/Los_Angeles', 2015, 3, 8, 3, 05) job.next_time = t1 occurrences = job.occurrences(t1, t2) expect(occurrences.length).to eq(11) end end context 'first_at/in' do it 'triggers for the first time at first_at' do t = Time.now job = @scheduler.schedule_every '3s', :first_in => '1s' do; end sleep 2 #p [ t, t.to_f ] #p [ job.last_time, job.last_time.to_f ] #p [ job.first_at, job.first_at.to_f ] expect(job.first_at).to be_within_1s_of(t + 2) expect(job.last_time).to be_within_1s_of(job.first_at) end describe '#first_at=' do it 'alters @next_time' do job = @scheduler.schedule_every '3s', :first_in => '10s' do; end fa0 = job.first_at nt0 = job.next_time job.first_at = Time.now + 3 fa1 = job.first_at nt1 = job.next_time expect(nt0).to eq(fa0) expect(nt1).to eq(fa1) end end end end rufus-scheduler-3.1.10/spec/job_in_spec.rb000066400000000000000000000003631262271731200204520ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'spec_helper' describe Rufus::Scheduler::InJob do before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end end rufus-scheduler-3.1.10/spec/job_interval_spec.rb000066400000000000000000000023231262271731200216660ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'spec_helper' describe Rufus::Scheduler::IntervalJob do before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end describe '#interval' do it 'returns the scheduled interval' do job = @scheduler.schedule_interval('1h') do; end expect(job.interval).to eq(3600) end end context 'first_at/in' do it 'triggers for the first time at first_at' do t = Time.now job = @scheduler.schedule_interval '3s', :first_in => '1s' do; end sleep 2 #p [ t, t.to_f ] #p [ job.last_time, job.last_time.to_f ] #p [ job.first_at, job.first_at.to_f ] expect(job.first_at).to be_within_1s_of(t + 2) expect(job.last_time).to be_within_1s_of(job.first_at) end describe '#first_at=' do it 'alters @next_time' do job = @scheduler.schedule_interval '3s', :first_in => '10s' do; end fa0 = job.first_at nt0 = job.next_time job.first_at = Time.now + 3 fa1 = job.first_at nt1 = job.next_time expect(nt0).to eq(fa0) expect(nt1).to eq(fa1) end end end end rufus-scheduler-3.1.10/spec/job_repeat_spec.rb000066400000000000000000000170411262271731200213250ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'spec_helper' describe Rufus::Scheduler::RepeatJob do before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end describe '#pause' do it 'pauses the job' do counter = 0 job = @scheduler.schedule_every('0.5s') do counter += 1 end expect(counter).to eq(0) while counter < 1; sleep(0.1); end job.pause sleep(1) expect(counter).to eq(1) end end describe '#paused?' do it 'returns true if the job is paused' do job = @scheduler.schedule_every('10s') do; end job.pause expect(job.paused?).to eq(true) end it 'returns false if the job is not paused' do job = @scheduler.schedule_every('10s') do; end expect(job.paused?).to eq(false) end end describe '#resume' do it 'resumes a paused job' do counter = 0 job = @scheduler.schedule_every('0.5s') do counter += 1 end job.pause job.resume sleep(1.5) expect(counter).to be > 1 end it 'has no effect on a not paused job' do job = @scheduler.schedule_every('10s') do; end job.resume expect(job.paused?).to eq(false) end end describe ':times => i' do it 'lets a job unschedule itself after i times' do counter = 0 job = @scheduler.schedule_every '0.5s', :times => 3 do counter = counter + 1 end sleep(2.6) expect(counter).to eq(3) end it 'is OK when passed a nil instead of an integer' do counter = 0 job = @scheduler.schedule_every '0.5s', :times => nil do counter = counter + 1 end sleep(2.5) expect(counter).to be > 3 end it 'raises when passed something else than nil or an integer' do expect { @scheduler.schedule_every '0.5s', :times => 'nada' do; end }.to raise_error(ArgumentError) end end describe ':first/:first_in/:first_at => point in time' do it 'accepts a Time instance' do t = Time.now + 10 job = @scheduler.schedule_every '0.5s', :first => t do; end expect(job.first_at).to eq(t) end it 'accepts a time string' do t = Time.now + 10 job = @scheduler.schedule_every '0.5s', :first => t.to_s do; end expect(job.first_at.to_s).to eq(t.to_s) expect(job.first_at.zone).to eq(t.zone) end it 'only lets the job trigger after the :first' do t = Time.now + 1.4 counter = 0 job = @scheduler.schedule_every '0.5s', :first => t do counter = counter + 1 end sleep(1) expect(counter).to eq(0) sleep(1) expect(counter).to be > 0 end it 'raises on points in the past' do expect { @scheduler.schedule_every '0.5s', :first => Time.now - 60 do; end }.to raise_error(ArgumentError) end context ':first_time => :now/:immediately/0' do it 'schedules the first execution immediately (:first => :now)' do n = Time.now ft = nil job = @scheduler.schedule_every '7s', :first => :now do ft ||= Time.now end sleep 0.7 expect(job.first_at).to be < n + 0.7 expect(ft).not_to eq(nil) expect(ft).to be < job.first_at + @scheduler.frequency + 0.1 end it 'schedules the first execution immediately (:first_in => 0)' do n = Time.now ft = nil job = @scheduler.schedule_every '7s', :first_in => 0 do ft ||= Time.now end sleep 0.7 expect(job.first_at).to be < n + 0.7 expect(ft).not_to eq(nil) expect(ft).to be < job.first_at + @scheduler.frequency + 0.1 end it 'schedules the first execution immediately (:first_in => "0s")' do n = Time.now ft = nil job = @scheduler.schedule_every '7s', :first_in => '0s' do ft ||= Time.now end sleep 0.7 expect(job.first_at).to be < n + 0.7 expect(ft).not_to eq(nil) expect(ft).to be < job.first_at + @scheduler.frequency + 0.1 end end end describe ':first/:first_in/:first_at => duration' do it 'accepts a duration string' do t = Time.now job = @scheduler.schedule_every '0.5s', :first => '1h' do; end expect(job.first_at).to be >= t + 3600 expect(job.first_at).to be < t + 3601 end it 'accepts a duration in seconds (integer)' do t = Time.now job = @scheduler.schedule_every '0.5s', :first => 3600 do; end expect(job.first_at).to be >= t + 3600 expect(job.first_at).to be < t + 3601 end it 'raises if the argument cannot be used' do expect { @scheduler.every '0.5s', :first => :nada do; end }.to raise_error(ArgumentError) end end describe '#first_at=' do it 'can be used to set first_at directly' do job = @scheduler.schedule_every '0.5s', :first => 3600 do; end job.first_at = '2030-12-12 12:00:30' expect(job.first_at.strftime('%c')).to eq('Thu Dec 12 12:00:30 2030') end end describe ':last/:last_in/:last_at => point in time' do it 'accepts a Time instance' do t = Time.now + 10 job = @scheduler.schedule_every '0.5s', :last => t do; end expect(job.last_at).to eq(t) end it 'unschedules the job after the last_at time' do t = Time.now + 2 counter = 0 tt = nil job = @scheduler.schedule_every '0.5s', :last => t do counter = counter + 1 tt = Time.now end sleep 3 #counter.should == 3 expect([ 3, 4 ]).to include(counter) expect(tt).to be < t expect(@scheduler.jobs).not_to include(job) end it 'accepts a time string' do t = Time.now + 10 job = @scheduler.schedule_every '0.5s', :last => t.to_s do; end expect(job.last_at.to_s).to eq(t.to_s) expect(job.last_at.zone).to eq(t.zone) end it 'raises on a point in the past' do expect { @scheduler.every '0.5s', :last => Time.now - 60 do; end }.to raise_error(ArgumentError) end end describe ':last/:last_in/:last_at => duration' do it 'accepts a duration string' do t = Time.now job = @scheduler.schedule_every '0.5s', :last_in => '2s' do; end expect(job.last_at).to be >= t + 2 expect(job.last_at).to be < t + 2.5 end it 'accepts a duration in seconds (integer)' do t = Time.now job = @scheduler.schedule_every '0.5s', :last_in => 2.0 do; end expect(job.last_at).to be >= t + 2 expect(job.last_at).to be < t + 2.5 end it 'raises if the argument is worthless' do expect { @scheduler.every '0.5s', :last => :nada do; end }.to raise_error(ArgumentError) end end describe '#last_at=' do it 'can be used to set last_at directly' do job = @scheduler.schedule_every '0.5s', :last_in => 10.0 do; end job.last_at = '2030-12-12 12:00:30' expect(job.last_at.strftime('%c')).to eq('Thu Dec 12 12:00:30 2030') end end describe '#count' do it 'starts at 0' do job = @scheduler.schedule_every '5m' do; end expect(job.count).to eq(0) end it 'keeps track of how many times the job fired' do job = @scheduler.schedule_every '0.5s' do; end sleep(2.0) expect(job.count).to be >= 3 expect(job.count).to be <= 4 end end end rufus-scheduler-3.1.10/spec/job_spec.rb000066400000000000000000000316431262271731200177710ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'spec_helper' describe Rufus::Scheduler::Job do # specify behaviours common to all job classes before :each do @taoe = Thread.abort_on_exception Thread.abort_on_exception = false @ose = $stderr $stderr = StringIO.new @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown Thread.abort_on_exception = @taoe $stderr = @ose end describe '#last_time' do it 'returns nil if the job never fired' do job = @scheduler.schedule_in '10d' do; end expect(job.last_time).to eq(nil) end it 'returns the last time the job fired' do job = @scheduler.schedule_in '0s' do; end sleep 0.4 expect(job.last_time).not_to eq(nil) end end describe '#threads' do it 'returns an empty list when the job is not running' do job = @scheduler.in('1d', :job => true) {} expect(job.threads.size).to eq(0) end it 'returns an empty list after the job terminated' do job = @scheduler.in('0s', :job => true) {} sleep 0.8 expect(job.threads.size).to eq(0) end it 'lists the threads the job currently runs in' do job = @scheduler.schedule_in('0s') do sleep(1) end sleep 0.4 expect(job.threads.size).to eq(1) t = job.threads.first expect(t[:rufus_scheduler_job]).to eq(job) end end describe '#kill' do it 'has no effect if the job is not running' do job = @scheduler.schedule_in '10d' do; end tls = Thread.list.size job.kill expect(Thread.list.size).to eq(tls) end it 'makes the threads vacant' do counter = 0 job = @scheduler.schedule_in '0s' do sleep 2 counter = counter + 1 end sleep 1 v0 = @scheduler.work_threads(:vacant).size a0 = @scheduler.work_threads(:active).size job.kill sleep 2 v1 = @scheduler.work_threads(:vacant).size a1 = @scheduler.work_threads(:active).size expect(counter).to eq(0) expect(v0).to eq(0) expect(a0).to eq(1) expect(v1).to eq(1) expect(a1).to eq(0) end end describe '#running?' do it 'returns false when the job is not running in any thread' do job = @scheduler.in('1d', :job => true) {} expect(job.running?).to eq(false) end it 'returns true when the job is running in at least one thread' do job = @scheduler.in('0s', :job => true) { sleep(1) } sleep 0.4 expect(job.running?).to eq(true) end end describe '#scheduled?' do it 'returns true when the job is scheduled' do job = @scheduler.schedule_in('1d') {} expect(job.scheduled?).to eq(true) end it 'returns false when the job is not scheduled' do job = @scheduler.schedule_in('0.1s') {} sleep 0.4 expect(job.scheduled?).to eq(false) end it 'returns true for repeat jobs that are running' do job = @scheduler.schedule_interval('0.4s') { sleep(10) } sleep 1 expect(job.running?).to eq(true) expect(job.scheduled?).to eq(true) end it 'returns false if job is unscheduled' do job = @scheduler.schedule_interval('0.1s') { sleep 0.1 } job.unschedule sleep 0.3 expect(job.running?).to eq(false) expect(job.scheduled?).to eq(false) end end describe '#call' do it 'calls the job (like it were a proc)' do counter = 0 job = @scheduler.schedule_in('0.5s') do counter = counter + 1 end job.call sleep 0.8 expect(counter).to eq(2) end end describe '#call(true)' do it 'calls the job and let the scheduler handle errors' do $err = nil def @scheduler.on_error(job, err) $err = "#{job.class} #{job.original} #{err.message}" rescue p $! end job = @scheduler.schedule_in('1d') do fail 'again' end job.call(true) expect($err).to eq('Rufus::Scheduler::InJob 1d again') end end describe '#call(false)' do it 'calls the job and let errors slip through' do job = @scheduler.schedule_in('1d') do fail 'fast' end begin #job.call(false) job.call # false is the default expect(false).to eq(true) rescue => ex expect(ex.message).to eq('fast') end end end context 'job-local variables' do describe '#[]=' do it 'sets a job-local variable' do job = @scheduler.schedule_every '1s' do |job| job[:counter] ||= 0 job[:counter] += 1 end sleep 3 expect(job[:counter]).to be > 1 end end describe '#[]' do it 'returns nil if there is no such entry' do job = @scheduler.schedule_in '1s' do; end expect(job[:nada]).to eq(nil) end it 'returns the value of a job-local variable' do job = @scheduler.schedule_in '1s' do; end job[:x] = :y expect(job[:x]).to eq(:y) end end describe '#key?' do it 'returns true if there is an entry with the given key' do job = @scheduler.schedule_in '1s' do; end job[:x] = :y expect(job.key?(:x)).to eq(true) end end describe '#keys' do it 'returns the array of keys of the job-local variables' do job = @scheduler.schedule_in '1s' do; end job[:x] = :y job['hello'] = :z job[123] = {} expect(job.keys.sort_by { |k| k.to_s }).to eq([ 123, 'hello', :x ]) end end end context ':tag / :tags => [ t0, t1 ]' do it 'accepts one tag' do job = @scheduler.in '10d', :job => true, :tag => 't0' do; end expect(job.tags).to eq(%w[ t0 ]) end it 'accepts an array of tags' do job = @scheduler.in '10d', :job => true, :tag => %w[ t0 t1 ] do; end expect(job.tags).to eq(%w[ t0 t1 ]) end it 'turns tags into strings' do job = @scheduler.in '10d', :job => true, :tags => [ 1, 2 ] do; end expect(job.tags).to eq(%w[ 1 2 ]) end end context ':blocking => true' do it 'runs the job in the same thread as the scheduler thread' do job = @scheduler.in('0s', :job => true, :blocking => true) do sleep(1) end sleep 0.4 expect(job.threads.first).to eq(@scheduler.thread) sleep 1.4 expect(job.threads.size).to eq(0) end end context 'default one thread per job behaviour' do it 'runs the job in a dedicated thread' do job = @scheduler.in('0s', :job => true) do sleep(1) end sleep 0.4 expect(job.threads.first).not_to eq(@scheduler.thread) sleep 1.4 expect(job.threads.size).to eq(0) end end context ':allow_overlapping / :allow_overlap / :overlap' do context 'default (:overlap => true)' do it 'lets a job overlap itself' do job = @scheduler.every('0.3', :job => true) do sleep(5) end sleep 3 expect(job.threads.size).to be > 1 end end context 'when :overlap => false' do it 'prevents a job from overlapping itself' do job = @scheduler.every('0.3', :job => true, :overlap => false) do sleep(5) end sleep 3 expect(job.threads.size).to eq(1) end end end context ':mutex' do context ':mutex => "mutex_name"' do it 'prevents concurrent executions' do j0 = @scheduler.in('0s', :job => true, :mutex => 'vladivostok') do sleep(3) end j1 = @scheduler.in('0s', :job => true, :mutex => 'vladivostok') do sleep(3) end sleep 0.7 if j0.threads.any? expect(j0.threads.size).to eq(1) expect(j1.threads.size).to eq(0) else expect(j0.threads.size).to eq(0) expect(j1.threads.size).to eq(1) end expect(@scheduler.mutexes.keys).to eq(%w[ vladivostok ]) end end context ':mutex => mutex_instance' do it 'prevents concurrent executions' do m = Mutex.new j0 = @scheduler.in('0s', :job => true, :mutex => m) { sleep(3) } j1 = @scheduler.in('0s', :job => true, :mutex => m) { sleep(3) } sleep 0.7 if j0.threads.any? expect(j0.threads.size).to eq(1) expect(j1.threads.size).to eq(0) else expect(j0.threads.size).to eq(0) expect(j1.threads.size).to eq(1) end expect(@scheduler.mutexes.keys).to eq([]) end end context ':mutex => [ array_of_mutex_names_or_instances ]' do it 'prevents concurrent executions' do j0 = @scheduler.in('0s', :job => true, :mutex => %w[ a b ]) do sleep(3) end j1 = @scheduler.in('0s', :job => true, :mutex => %w[ a b ]) do sleep(3) end sleep 0.7 if j0.threads.any? expect(j0.threads.size).to eq(1) expect(j1.threads.size).to eq(0) else expect(j0.threads.size).to eq(0) expect(j1.threads.size).to eq(1) end expect(@scheduler.mutexes.keys.sort).to eq(%w[ a b ]) end end end context ':timeout => duration_or_point_in_time' do it 'interrupts the job it is stashed to (duration)' do counter = 0 toe = nil job = @scheduler.schedule_in '0s', :timeout => '1s' do begin counter = counter + 1 sleep 1.5 counter = counter + 1 rescue Rufus::Scheduler::TimeoutError => e toe = e end end sleep(3) expect(counter).to eq(1) expect(toe.class).to eq(Rufus::Scheduler::TimeoutError) end it 'interrupts the job it is stashed to (point in time)' do counter = 0 job = @scheduler.schedule_in '0s', :timeout => Time.now + 1 do begin counter = counter + 1 sleep 1.5 counter = counter + 1 rescue Rufus::Scheduler::TimeoutError => e end end sleep(3) expect(counter).to eq(1) end it 'starts timing when the job enters successfully all its mutexes' do t0, t1, t2 = nil @scheduler.schedule_in '0s', :mutex => 'a' do sleep 1 t0 = Time.now end job = @scheduler.schedule_in '0.5s', :mutex => 'a', :timeout => '1s' do begin t1 = Time.now sleep 2 rescue Rufus::Scheduler::TimeoutError => e t2 = Time.now end end sleep 3 expect(t0).to be <= t1 d = t2 - t1 expect(d).to be >= 1.0 expect(d).to be < 1.5 end it 'emits the timeout information to $stderr (default #on_error)' do @scheduler.every('1s', :timeout => '0.5s') do sleep 0.9 end sleep 2 expect($stderr.string).to match(/Rufus::Scheduler::TimeoutError/) end it 'does not prevent a repeat job from recurring' do counter = 0 @scheduler.every('1s', :timeout => '0.5s') do counter = counter + 1 sleep 0.9 end sleep 3 expect(counter).to be > 1 end end context 'work time' do describe '#last_work_time' do it 'starts at 0' do job = @scheduler.schedule_every '5m' do; end expect(job.last_work_time).to eq(0.0) end it 'keeps track of how long the work was upon last trigger' do job = @scheduler.schedule_in '0.5s' do sleep 0.7 end sleep 2 expect(job.last_work_time).to be >= 0.7 expect(job.last_work_time).to be < 0.8 end end describe '#mean_work_time' do it 'starts at 0' do job = @scheduler.schedule_every '5m' do; end expect(job.mean_work_time).to eq(0.0) end it 'gathers work times and computes the mean' do job = @scheduler.schedule_every '0.5s' do |j| #p j.last_work_time #p j.mean_work_time sleep 0.01 * (j.count + 1) end sleep 4.6 expect(job.last_work_time).to be >= 0.08 expect(job.last_work_time).to be < 0.099 expect(job.mean_work_time).to be > 0.05 expect(job.mean_work_time).to be < 0.06 end end end context 'one time job' do describe '#determine_id' do it 'returns unique ids' do ids = [] 10_000.times { ids << @scheduler.in('1y') {} } expect(ids.uniq.length).to eq(ids.length) end end end context 'repeat job' do describe '#determine_id' do it 'returns unique ids' do ids = [] 10_000.times { ids << @scheduler.every('1y') {} } expect(ids.uniq.length).to eq(ids.length) end end end end rufus-scheduler-3.1.10/spec/lock_custom_spec.rb000066400000000000000000000011661262271731200215360ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Fri Nov 1 05:56:03 JST 2013 # # Ishinomaki # require 'spec_helper' describe Rufus::Scheduler do class LosingLockScheduler < Rufus::Scheduler attr_reader :counter def initialize super @counter = 0 end def confirm_lock @counter = @counter + 1 false end end context 'custom locks' do it 'does not trigger when #confirm_lock returns false' do s = LosingLockScheduler.new count = 0 s.in('0s') { count = count + 1 } sleep 0.7 expect(count).to eq(0) expect(s.counter).to eq(1) end end end rufus-scheduler-3.1.10/spec/lock_flock_spec.rb000066400000000000000000000013751262271731200213240ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Sat Aug 16 05:43:06 JST 2014 # added by @ecin # require 'spec_helper' describe Rufus::Scheduler::FileLock do before :each do @lock_path = '.rufus-scheduler.lock' @lock = Rufus::Scheduler::FileLock.new(@lock_path) end after :each do FileUtils.rm_f(@lock_path) FileUtils.rm_f('lock.txt') end context ':scheduler_lock => Rufus::Scheduler::FileLock.new(path)' do it 'writes down a .rufus-scheduler.lock file' do @lock.lock line = File.read(@lock_path) expect(line).to match(/pid: #{$$}/) end it '"flocks" the lock file' do @lock.lock f = File.new(@lock_path, 'a') expect(f.flock(File::LOCK_NB | File::LOCK_EX)).to eq(false) end end end rufus-scheduler-3.1.10/spec/lock_lockfile_spec.rb000066400000000000000000000024301262271731200220070ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Tue Aug 13 05:58:48 JST 2013 # require 'spec_helper' describe Rufus::Scheduler do after :each do FileUtils.rm_f('.rufus-scheduler.lock') FileUtils.rm_f('lock.txt') end context ':lockfile => ".rufus-scheduler.lock"' do it 'writes down a .rufus-scheduler.lock file' do s = Rufus::Scheduler.new :lockfile => '.rufus-scheduler.lock' line = File.read('.rufus-scheduler.lock') #p line expect(line).to match(/pid: #{$$}/) end it '"flocks" the lock file' do s = Rufus::Scheduler.new :lockfile => '.rufus-scheduler.lock' f = File.new('.rufus-scheduler.lock', 'a') expect(f.flock(File::LOCK_NB | File::LOCK_EX)).to eq(false) end it 'prevents newer schedulers from starting' do s0 = Rufus::Scheduler.new :lockfile => '.rufus-scheduler.lock' s1 = Rufus::Scheduler.new :lockfile => '.rufus-scheduler.lock' expect(s0.started_at).not_to eq(nil) expect(s1.started_at).to eq(nil) end it 'releases the lockfile when shutting down' do s = Rufus::Scheduler.new :lockfile => '.rufus-scheduler.lock' s.shutdown(:kill) f = File.new('.rufus-scheduler.lock', 'a') expect(f.flock(File::LOCK_NB | File::LOCK_EX)).to eq(0) end end end rufus-scheduler-3.1.10/spec/lock_spec.rb000066400000000000000000000023701262271731200201420ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Sat Aug 16 05:42:11 JST 2014 # added by @ecin # require 'spec_helper' describe Rufus::Scheduler do context "when running multiple schedulers side-by-side" do class AlwaysLock def lock; true; end def unlock; true; end def locked?; true; end end class NeverLock def lock; false; end def unlock; true; end def locked?; true; end end it "only starts if it can acquire a scheduler lock" do main = Rufus::Scheduler.new :scheduler_lock => AlwaysLock.new backup = Rufus::Scheduler.new :scheduler_lock => NeverLock.new expect(main).to be_up expect(backup).to be_down end it "only triggers jobs when it can acquire a trigger lock" do main = Rufus::Scheduler.new(:trigger_lock => AlwaysLock.new) backup = Rufus::Scheduler.new(:trigger_lock => NeverLock.new) expect(main).to be_up expect(backup).to be_up counter = 0 job = proc { counter += 1 } main.schedule_in(0, job) backup.schedule_in(0, job) sleep 0.5 expect(main.jobs).to be_empty expect(backup.jobs.count).to eq(1) expect(backup.jobs.first.next_time).to be(false) expect(counter).to eq(1) end end end rufus-scheduler-3.1.10/spec/parse_spec.rb000066400000000000000000000146471262271731200203360ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'spec_helper' describe Rufus::Scheduler do describe '.parse' do def pa(s, opts={}); Rufus::Scheduler.parse(s, opts); end it 'parses duration strings' do expect(pa('1.0d1.0w1.0d')).to eq(777600.0) end it 'parses datetimes' do # local expect(pa('Sun Nov 18 16:01:00 2012').strftime('%c')).to eq( 'Sun Nov 18 16:01:00 2012' ) end it 'parses datetimes with timezones' do expect( pa('Sun Nov 18 16:01:00 2012 Asia/Singapore').getutc.strftime('%c %z') ).to eq('Sun Nov 18 08:01:00 2012 +0000') expect(pa('Sun Nov 18 16:01:00 2012 Zulu').getutc.strftime('%c')).to eq( 'Sun Nov 18 16:01:00 2012' ) expect( pa('Sun Nov 18 16:01:00 Asia/Singapore 2012').getutc.strftime('%c %z') ).to eq('Sun Nov 18 08:01:00 2012 +0000') expect( pa('Asia/Singapore Sun Nov 18 16:01:00 2012').getutc.strftime('%c %z') ).to eq('Sun Nov 18 08:01:00 2012 +0000') expect( pa('Sun Nov 18 16:01:00 2012 America/New_York').getutc.strftime('%c %z') ).to eq('Sun Nov 18 21:01:00 2012 +0000') end it 'parses datetimes with named timezones' do expect(pa( 'Sun Nov 18 16:01:00 2012 Europe/Berlin' ).strftime('%c %z')).to eq( 'Sun Nov 18 16:01:00 2012 +0100' ) end it 'parses datetimes (with the local timezone implicitely)' do localzone = Time.now.strftime('%z') expect( pa('Nov 18 16:01:00 2012').strftime('%c %z') ).to eq("Sun Nov 18 16:01:00 2012 #{localzone}") end it 'parses cronlines' do out = pa('* * * * *') expect(out.class).to eq(Rufus::Scheduler::CronLine) expect(out.original).to eq('* * * * *') expect(pa('10 23 * * *').class).to eq(Rufus::Scheduler::CronLine) expect(pa('* 23 * * *').class).to eq(Rufus::Scheduler::CronLine) end it 'raises on unparseable input' do expect { pa('nada') }.to raise_error(ArgumentError, 'couldn\'t parse "nada"') end it 'does not use Chronic if not present' do t = pa('next monday 7 PM') n = Time.now expect(t.strftime('%Y-%m-%d %H:%M:%S')).to eq( n.strftime('%Y-%m-%d') + ' 19:00:00' ) end it 'uses Chronic if present' do with_chronic do t = pa('next monday 7 PM') expect(t.wday).to eq(1) expect(t.hour).to eq(19) expect(t.min).to eq(0) expect(t).to be > Time.now end end it 'passes options to Chronic' do with_chronic do t = pa('monday', :context => :past) expect(t.wday).to eq(1) expect(t).to be < Time.now end end end describe '.parse_duration' do def pd(s) Rufus::Scheduler.parse_duration(s) end it 'parses duration strings' do expect(pd('-1.0d1.0w1.0d')).to eq(-777600.0) expect(pd('-1d1w1d')).to eq(-777600.0) expect(pd('-1w2d')).to eq(-777600.0) expect(pd('-1h10s')).to eq(-3610.0) expect(pd('-1h')).to eq(-3600.0) expect(pd('-5.')).to eq(-5.0) expect(pd('-2.5s')).to eq(-2.5) expect(pd('-1s')).to eq(-1.0) expect(pd('-500')).to eq(-500) expect(pd('')).to eq(0.0) expect(pd('5.0')).to eq(5.0) expect(pd('0.5')).to eq(0.5) expect(pd('.5')).to eq(0.5) expect(pd('5.')).to eq(5.0) expect(pd('500')).to eq(500) expect(pd('1000')).to eq(1000) expect(pd('1')).to eq(1.0) expect(pd('1s')).to eq(1.0) expect(pd('2.5s')).to eq(2.5) expect(pd('1h')).to eq(3600.0) expect(pd('1h10s')).to eq(3610.0) expect(pd('1w2d')).to eq(777600.0) expect(pd('1d1w1d')).to eq(777600.0) expect(pd('1.0d1.0w1.0d')).to eq(777600.0) expect(pd('.5m')).to eq(30.0) expect(pd('5.m')).to eq(300.0) expect(pd('1m.5s')).to eq(60.5) expect(pd('-.5m')).to eq(-30.0) expect(pd('1')).to eq(1) expect(pd('0.1')).to eq(0.1) expect(pd('1s')).to eq(1) end it 'calls #to_s on its input' do expect(pd(0.1)).to eq(0.1) end it 'raises on wrong duration strings' do expect { pd('-') }.to raise_error(ArgumentError) expect { pd('h') }.to raise_error(ArgumentError) expect { pd('whatever') }.to raise_error(ArgumentError) expect { pd('hms') }.to raise_error(ArgumentError) expect { pd(' 1h ') }.to raise_error(ArgumentError) end end describe '.parse_time_string -> .parse_duration' do it 'is still around for libs using it out there' do expect(Rufus::Scheduler.parse_time_string('1d1w1d')).to eq(777600.0) end end describe '.parse_duration_string -> .parse_duration' do it 'is still around for libs using it out there' do expect(Rufus::Scheduler.parse_duration_string('1d1w1d')).to eq(777600.0) end end describe '.to_duration' do def td(o, opts={}) Rufus::Scheduler.to_duration(o, opts) end it 'turns integers into duration strings' do expect(td(0)).to eq('0s') expect(td(60)).to eq('1m') expect(td(61)).to eq('1m1s') expect(td(3661)).to eq('1h1m1s') expect(td(24 * 3600)).to eq('1d') expect(td(7 * 24 * 3600 + 1)).to eq('1w1s') expect(td(30 * 24 * 3600 + 1)).to eq('4w2d1s') end it 'ignores seconds and milliseconds if :drop_seconds => true' do expect(td(0, :drop_seconds => true)).to eq('0m') expect(td(5, :drop_seconds => true)).to eq('0m') expect(td(61, :drop_seconds => true)).to eq('1m') end it 'displays months if :months => true' do expect(td(1, :months => true)).to eq('1s') expect(td(30 * 24 * 3600 + 1, :months => true)).to eq('1M1s') end it 'turns floats into duration strings' do expect(td(0.1)).to eq('100') expect(td(1.1)).to eq('1s100') end end describe '.to_duration_hash' do def tdh(o, opts={}) Rufus::Scheduler.to_duration_hash(o, opts) end it 'turns integers duration hashes' do expect(tdh(0)).to eq({}) expect(tdh(60)).to eq({ :m => 1 }) end it 'turns floats duration hashes' do expect(tdh(0.128)).to eq({ :ms => 128 }) expect(tdh(60.127)).to eq({ :m => 1, :ms => 127 }) end it 'drops seconds and milliseconds if :drop_seconds => true' do expect(tdh(61.127)).to eq({ :m => 1, :s => 1, :ms => 127 }) expect(tdh(61.127, :drop_seconds => true)).to eq({ :m => 1 }) end end end rufus-scheduler-3.1.10/spec/schedule_at_spec.rb000066400000000000000000000062321262271731200214730ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'spec_helper' describe Rufus::Scheduler do before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end describe '#at' do it 'raises if the block to schedule is missing' do expect { @scheduler.at(Time.now + 3600) }.to raise_error(ArgumentError) end it 'returns a job id' do job_id = @scheduler.at(Time.now + 3600) do end expect(job_id.class).to eq(String) expect(job_id).to match(/^at_/) end it 'returns a job if :job => true' do job = @scheduler.at(Time.now + 3600, :job => true) do end expect(job.class).to eq(Rufus::Scheduler::AtJob) end it 'adds a job' do t = Time.now + 3600 @scheduler.at(t) do end expect(@scheduler.jobs.size).to eq(1) expect(@scheduler.jobs.first.class).to eq(Rufus::Scheduler::AtJob) expect(@scheduler.jobs.first.time).to eq(t) end it 'triggers a job' do a = false @scheduler.at(Time.now + 0.100) do a = true end sleep 0.4 expect(a).to eq(true) end it 'removes the job after execution' do @scheduler.at(Time.now + 0.100) do end sleep 0.4 expect(@scheduler.jobs.size).to eq(0) end it 'accepts a Time instance' do t = Time.now + 3600 job = @scheduler.at(t, :job => true) {} expect(job.time).to eq(t) end it 'accepts a time string' do job = @scheduler.at('2100-12-12 20:30', :job => true) {} expect(job.time).to eq(Time.parse('2100-12-12 20:30')) end it 'accepts a time string with a delta timezone' do job = @scheduler.at('2100-12-12 20:30 -0200', :job => true) {} expect(job.time).to eq(Time.parse('2100-12-12 20:30 -0200')) end it 'accepts a time string with a named timezone' do job = @scheduler.at('2050-12-12 20:30 Europe/Berlin', :job => true) {} expect(job.time.strftime('%c %z')).to eq('Mon Dec 12 20:30:00 2050 +0100') end it 'accepts a Chronic string (if Chronic is present)' do with_chronic do job = @scheduler.schedule_at('next tuesday at 12:00') {} expect(job.time.wday).to eq(2) expect(job.time.hour).to eq(12) expect(job.time.min).to eq(0) expect(job.time).to be > Time.now end end it 'accepts a Chronic string and Chronic options (if Chronic present)' do with_chronic do job = @scheduler.schedule_at( 'may 27th at 12:00', :now => Time.local(Time.now.year + 2, 1, 1) ) {} expect(job.time.year).to eq(Time.now.year + 2) expect(job.time.month).to eq(5) expect(job.time.day).to eq(27) expect(job.time.hour).to eq(12) expect(job.time.min).to eq(0) end end it 'accepts an ActiveSupport time thinggy' end describe '#schedule_at' do it 'returns a job' do job = @scheduler.schedule_at(Time.now + 3600) do end expect(job.class).to eq(Rufus::Scheduler::AtJob) expect(job.id).to match(/^at_/) end end end rufus-scheduler-3.1.10/spec/schedule_cron_spec.rb000066400000000000000000000023701262271731200220270ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Sat Jul 13 04:52:08 JST 2013 # # In the train between Bern and Fribourg, riding back # from the @ruvetia drinkup # require 'spec_helper' describe Rufus::Scheduler do before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end describe '#cron' do it 'schedules' do counter = 0 sleep_until_next_second sleep 0.3 # make sure to schedule right after a scheduler 'tick' job = @scheduler.cron '* * * * * *', :job => true do counter = counter + 1 end sleep_until_next_second sleep_until_next_second sleep 0.3 # be sure to be well into the second expect(counter).to eq(2) end it 'raises if the job frequency is higher than the scheduler frequency' do @scheduler.frequency = 10 expect { @scheduler.cron '* * * * * *' do; end }.to raise_error(ArgumentError) end end describe '#schedule_cron' do it 'returns a CronJob instance' do job = @scheduler.schedule_cron '* * * * *' do; end expect(job.class).to eq(Rufus::Scheduler::CronJob) expect(job.original).to eq('* * * * *') expect(job.job_id).to match(/^cron_/) end end end rufus-scheduler-3.1.10/spec/schedule_every_spec.rb000066400000000000000000000033731262271731200222240ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'spec_helper' describe Rufus::Scheduler do before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end describe '#every' do it 'adds a job' do @scheduler.every(10) do end expect(@scheduler.jobs.size).to eq(1) expect(@scheduler.jobs.first.class).to eq(Rufus::Scheduler::EveryJob) end it 'triggers a job (2 times)' do counter = 0 @scheduler.every(0.4) do counter += 1 end sleep 2.0 expect(counter).to be > 2 end it 'does not remove the job after execution' do @scheduler.every(0.4) do end sleep 0.9 expect(@scheduler.jobs.size).to eq(1) end it 'raises on negative frequencies' do expect { @scheduler.every(-1) do end }.to raise_error(ArgumentError) end it 'raises on zero frequencies' do expect { @scheduler.every(0) do end }.to raise_error(ArgumentError) end it 'does not reschedule if the job was unscheduled' do counter = 0 job = @scheduler.schedule_every '0.5s' do counter = counter + 1 end sleep 1.6 job.unschedule c = counter sleep 1.6 expect(counter).to eq(c) end it 'raises if the job frequency is higher than the scheduler frequency' do @scheduler.frequency = 10 expect { @scheduler.every '1s' do; end }.to raise_error(ArgumentError) end end describe '#schedule_every' do it 'accepts a duration string' do job = @scheduler.schedule_every('1h') do; end expect(job.frequency).to eq(3600.0) end end end rufus-scheduler-3.1.10/spec/schedule_in_spec.rb000066400000000000000000000024671262271731200215030ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'spec_helper' describe Rufus::Scheduler do before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end describe '#in' do it 'adds a job' do @scheduler.in(3600) do end expect(@scheduler.jobs.size).to eq(1) expect(@scheduler.jobs.first.class).to eq(Rufus::Scheduler::InJob) end it 'triggers a job' do a = false @scheduler.in(0.4) do a = true end sleep 0.9 expect(a).to eq(true) end it 'removes the job after execution' do @scheduler.in(0.4) do end sleep 0.700 expect(@scheduler.jobs.size).to eq(0) end end describe '#schedule_in' do it 'accepts a number' do job = @scheduler.schedule_in(3600) {} expect(job.original).to eq(3600) end it 'accepts a duration string' do job = @scheduler.schedule_in('1h') {} expect(job.original).to eq('1h') expect(job.time).to be >= job.scheduled_at + 3509 expect(job.time).to be <= job.scheduled_at + 3601 end it 'accepts an ActiveSupport .from_now thinggy' # # schedule_in(2.days.from_now) # # that'd simply require "in" to be a bit like "at"... end end rufus-scheduler-3.1.10/spec/schedule_interval_spec.rb000066400000000000000000000043751262271731200227210ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Aug 7 06:20:55 JST 2013 # require 'spec_helper' describe Rufus::Scheduler do before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end describe '#interval' do it 'adds a job' do @scheduler.interval(10) do end expect(@scheduler.jobs.size).to eq(1) expect(@scheduler.jobs.first.class).to eq(Rufus::Scheduler::IntervalJob) end it 'triggers a job (2 times)' do counter = 0 @scheduler.interval(0.4) do counter += 1 end sleep 2.0 expect(counter).to be > 2 end it 'triggers, but reschedules after the trigger execution' do chronos = [] @scheduler.interval(0.4) do now = Time.now last, delta = chronos.last chronos << [ now, last ? now - last : nil ] sleep 0.5 end t = Time.now sleep 0.1 while chronos.size < 4 && Time.now < t + 5 expect(chronos.size).to eq(4) deltas = chronos.collect(&:last).compact #pp chronos #pp deltas deltas.each do |d| expect(d).to be >= 0.9 end end it 'does not reschedule if the job was unscheduled' do counter = 0 job = @scheduler.schedule_interval '0.5s' do counter = counter + 1 end sleep 1.6 expect(@scheduler.jobs(:all).size).to eq(1) job.unschedule c = counter sleep 1.6 expect(counter).to eq(c) expect(@scheduler.jobs(:all).size).to eq(0) end it 'raises on negative intervals' do expect { @scheduler.interval(-1) do end }.to raise_error(ArgumentError) end it 'raises on zero intervals' do expect { @scheduler.interval(0) do end }.to raise_error(ArgumentError) end #it 'raises if the job frequency is higher than the scheduler frequency' do # # @scheduler.frequency = 10 # # lambda { # @scheduler.interval '1s' do; end # }.should raise_error(ArgumentError) #end end describe '#schedule_interval' do it 'accepts a duration string' do job = @scheduler.schedule_interval('1h') do; end expect(job.interval).to eq(3600) end end end rufus-scheduler-3.1.10/spec/scheduler_spec.rb000066400000000000000000000542141262271731200211740ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'spec_helper' describe Rufus::Scheduler do describe '#initialize' do it 'starts the scheduler thread' do scheduler = Rufus::Scheduler.new t = Thread.list.find { |t| t[:name] == "rufus_scheduler_#{scheduler.object_id}_scheduler" } expect(t[:rufus_scheduler]).to eq(scheduler) end it 'sets :name and :rufus_scheduler in the scheduler thread local vars' do scheduler = Rufus::Scheduler.new expect(scheduler.thread[:name]).to eq( "rufus_scheduler_#{scheduler.object_id}_scheduler" ) expect(scheduler.thread[:rufus_scheduler]).to eq( scheduler ) end it 'accepts a :frequency => integer option' do scheduler = Rufus::Scheduler.new(:frequency => 2) expect(scheduler.frequency).to eq(2) end it 'accepts a :frequency => "2h1m" option' do scheduler = Rufus::Scheduler.new(:frequency => '2h1m') expect(scheduler.frequency).to eq(3600 * 2 + 60) end it 'accepts a :thread_name option' do scheduler = Rufus::Scheduler.new(:thread_name => 'oliphant') t = Thread.list.find { |t| t[:name] == 'oliphant' } expect(t[:rufus_scheduler]).to eq(scheduler) end #it 'accepts a :min_work_threads option' do # scheduler = Rufus::Scheduler.new(:min_work_threads => 9) # scheduler.min_work_threads.should == 9 #end it 'accepts a :max_work_threads option' do scheduler = Rufus::Scheduler.new(:max_work_threads => 9) expect(scheduler.max_work_threads).to eq(9) end end before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end describe 'a schedule method' do it 'passes the job to its block when it triggers' do j = nil job = @scheduler.schedule_in('0s') { |jj| j = jj } sleep 0.4 expect(j).to eq(job) end it 'passes the trigger time as second block argument' do t = nil @scheduler.schedule_in('0s') { |jj, tt| t = tt } sleep 0.4 expect(t.class).to eq(Time) end class MyHandler attr_reader :counter def initialize @counter = 0 end def call(job, time) @counter = @counter + 1 end end it 'accepts a callable object instead of a block' do mh = MyHandler.new @scheduler.schedule_in('0s', mh) sleep 0.4 expect(mh.counter).to eq(1) end class MyOtherHandler attr_reader :counter def initialize @counter = 0 end def call @counter = @counter + 1 end end it 'accepts a callable obj instead of a block (#call with no args)' do job = @scheduler.schedule_in('0s', MyOtherHandler.new) sleep 0.4 expect(job.handler.counter).to eq(1) end it 'accepts a class as callable' do job = @scheduler.schedule_in('0s', Class.new do attr_reader :value def call @value = 7 end end) sleep 0.4 expect(job.handler.value).to eq(7) end it 'raises if the scheduler is shutting down' do @scheduler.shutdown expect { @scheduler.in('0s') { puts 'hhhhhhhhhhhello!!' } }.to raise_error(Rufus::Scheduler::NotRunningError) end end describe '#in / #at' do # scheduler.in(2.hours.from_now) { ... } it 'accepts point in time and duration indifferently (#in)' do seen = false t = Time.now + 1 @scheduler.in(t) { seen = true } sleep 0.1 while seen != true end it 'accepts point in time and duration indifferently (#at)' do seen = false t = 1 @scheduler.at(t) { seen = true } sleep 0.1 while seen != true end end describe '#schedule' do it 'accepts a duration and schedules an InJob' do j = @scheduler.schedule '1s' do; end expect(j.class).to eq(Rufus::Scheduler::InJob) expect(j.original).to eq('1s') end it 'accepts a point in time and schedules an AtJob' do j = @scheduler.schedule '2070/12/24 23:00' do; end expect(j.class).to eq(Rufus::Scheduler::AtJob) expect(j.next_time.strftime('%Y %m %d')).to eq('2070 12 24') end it 'accepts a cron string and schedules a CronJob' do j = @scheduler.schedule '* * * * *' do; end expect(j.class).to eq(Rufus::Scheduler::CronJob) end end describe '#repeat' do it 'accepts a duration and schedules an EveryJob' do j = @scheduler.repeat '1s' do; end expect(j.class).to eq(Rufus::Scheduler::EveryJob) end it 'accepts a cron string and schedules a CronJob' do j = @scheduler.repeat '* * * * *' do; end expect(j.class).to eq(Rufus::Scheduler::CronJob) end end describe '#unschedule(job_or_work_id)' do it 'accepts job ids' do job = @scheduler.schedule_in '10d' do; end expect(job.unscheduled_at).to eq(nil) @scheduler.unschedule(job.id) expect(job.unscheduled_at).not_to eq(nil) end it 'accepts jobs' do job = @scheduler.schedule_in '10d' do; end expect(job.unscheduled_at).to eq(nil) @scheduler.unschedule(job) expect(job.unscheduled_at).not_to eq(nil) end it 'carefully unschedules repeat jobs' do counter = 0 job = @scheduler.schedule_every '0.5s' do counter = counter + 1 end sleep 1.5 c = counter @scheduler.unschedule(job) sleep 1.5 expect(counter).to eq(c) end end describe '#uptime' do it 'returns the uptime as a float' do expect(@scheduler.uptime).to be >= 0.0 end end describe '#uptime_s' do it 'returns the uptime as a human readable string' do sleep 1 expect(@scheduler.uptime_s).to match(/^[12]s\d+$/) end end describe '#join' do it 'joins the scheduler thread' do t = Thread.new { @scheduler.join; Thread.current['a'] = 'over' } expect(t['a']).to eq(nil) @scheduler.shutdown sleep(1) expect(t['a']).to eq('over') end end describe '#job(job_id)' do it 'returns nil if there is no corresponding Job instance' do expect(@scheduler.job('nada')).to eq(nil) end it 'returns the corresponding Job instance' do job_id = @scheduler.in '10d' do; end sleep(1) # give it some time to get scheduled expect(@scheduler.job(job_id).job_id).to eq(job_id) end end # describe '#find_by_tag(t)' do # # it 'returns an empty list when there are no jobs with the given tag' do # # @scheduler.find_by_tag('nada').should == [] # end # # it 'returns all the jobs with the given tag' do # # @scheduler.in '10d', :tag => 't0' do; end # @scheduler.every '2h', :tag => %w[ t0 t1 ] do; end # @scheduler.every '3h' do; end # # @scheduler.find_by_tag('t0').map(&:original).should == # %w[ 2h 10d ] # @scheduler.find_by_tag('t1').map(&:original).should == # %w[ 2h ] # @scheduler.find_by_tag('t1', 't0').map(&:original).sort.should == # %w[ 2h ] # end # end describe '#threads' do it 'just lists the main thread (scheduler thread) when no job is scheduled' do expect(@scheduler.threads).to eq([ @scheduler.thread ]) end it 'lists all the threads a scheduler uses' do @scheduler.in '0s' do sleep(2) end sleep 0.4 expect(@scheduler.threads.size).to eq(2) end end describe '#work_threads(:all | :vacant)' do it 'returns an empty array when the scheduler has not yet done anything' do expect(@scheduler.work_threads).to eq([]) expect(@scheduler.work_threads(:all)).to eq([]) expect(@scheduler.work_threads(:vacant)).to eq([]) end it 'lists the [vacant] work threads in the pool' do @scheduler.in '0s' do sleep(0.2) end @scheduler.in '0s' do sleep(2.0) end sleep 0.7 if @scheduler.work_threads.size == 1 expect(@scheduler.work_threads.size).to eq(1) expect(@scheduler.work_threads(:all).size).to eq(1) expect(@scheduler.work_threads(:vacant).size).to eq(0) else expect(@scheduler.work_threads.size).to eq(2) expect(@scheduler.work_threads(:all).size).to eq(2) expect(@scheduler.work_threads(:vacant).size).to eq(1) end end end describe '#work_threads(:active)' do it 'returns [] when there are no jobs running' do expect(@scheduler.work_threads(:active)).to eq([]) end it 'returns the list of threads of the running jobs' do job = @scheduler.schedule_in('0s') do sleep 1 end sleep 0.4 expect(@scheduler.work_threads(:active).size).to eq(1) t = @scheduler.work_threads(:active).first expect(t.class).to eq(Thread) expect(t[@scheduler.thread_key]).to eq(true) expect(t[:rufus_scheduler_job]).to eq(job) expect(t[:rufus_scheduler_time]).not_to eq(nil) end it 'does not return threads from other schedulers' do scheduler = Rufus::Scheduler.new job = @scheduler.schedule_in('0s') do sleep(1) end sleep 0.4 expect(scheduler.work_threads(:active)).to eq([]) scheduler.shutdown end end #describe '#min_work_threads' do # it 'returns the min job thread count' do # @scheduler.min_work_threads.should == 3 # end #end #describe '#min_work_threads=' do # it 'sets the min job thread count' do # @scheduler.min_work_threads = 1 # @scheduler.min_work_threads.should == 1 # end #end describe '#max_work_threads' do it 'returns the max job thread count' do expect(@scheduler.max_work_threads).to eq(28) end end describe '#max_work_threads=' do it 'sets the max job thread count' do @scheduler.max_work_threads = 14 expect(@scheduler.max_work_threads).to eq(14) end end #describe '#kill_all_work_threads' do # # it 'kills all the work threads' do # # @scheduler.in '0s' do; sleep(5); end # @scheduler.in '0s' do; sleep(5); end # @scheduler.in '0s' do; sleep(5); end # # sleep 0.5 # # @scheduler.work_threads.size.should == 3 # # @scheduler.send(:kill_all_work_threads) # # sleep 0.5 # # @scheduler.work_threads.size.should == 0 # end #end describe '#running_jobs' do it 'returns [] when there are no running jobs' do expect(@scheduler.running_jobs).to eq([]) end it 'returns a list of running Job instances' do job = @scheduler.schedule_in('0s') do sleep(1) end sleep 0.4 expect(job.running?).to eq(true) expect(@scheduler.running_jobs).to eq([ job ]) end it 'does not return twice the same job' do job = @scheduler.schedule_every('0.3s') do sleep(5) end sleep 1.5 expect(job.running?).to eq(true) expect(@scheduler.running_jobs).to eq([ job ]) end end describe '#running_jobs(:tag/:tags => x)' do it 'returns a list of running jobs filtered by tag' do @scheduler.in '0.1s', :tag => 't0' do sleep 3 end @scheduler.in '0.2s', :tag => 't1' do sleep 3 end sleep 0.49 expect(@scheduler.running_jobs(:tag => 't0').map(&:original)).to eq( %w[ 0.1s ] ) expect(@scheduler.running_jobs(:tag => 't1').map(&:original)).to eq( %w[ 0.2s ] ) expect(@scheduler.running_jobs(:tags => %w[ t0 t1 ]).map(&:original)).to eq( [] ) end end describe '#occurrences(time0, time1)' do it 'returns a { job => [ times ] } of job occurrences' do j0 = @scheduler.schedule_in '7m' do; end j1 = @scheduler.schedule_at '10m' do; end j2 = @scheduler.schedule_every '5m' do; end j3 = @scheduler.schedule_interval '5m' do; end j4 = @scheduler.schedule_cron '* * * * *' do; end h = @scheduler.occurrences(Time.now + 4 * 60, Time.now + 11 * 60) expect(h.size).to eq(5) expect(h[j0]).to eq([ j0.next_time ]) expect(h[j1]).to eq([ j1.next_time ]) expect(h[j2].size).to eq(2) expect(h[j3].size).to eq(2) expect(h[j4].size).to eq(7) end it 'returns a [ [ time, job ], ... ] of job occurrences when :timeline' do j0 = @scheduler.schedule_in '5m' do; end j1 = @scheduler.schedule_in '10m' do; end a = @scheduler.occurrences(Time.now + 4 * 60, Time.now + 11 * 60, :timeline) expect(a[0][0]).to be_within_1s_of(Time.now + 5 * 60) expect(a[0][1]).to eq(j0) expect(a[1][0]).to be_within_1s_of(Time.now + 10 * 60) expect(a[1][1]).to eq(j1) end it 'respects :first_at for repeat jobs' do j0 = @scheduler.schedule_every '5m', :first_in => '10m' do; end h = @scheduler.occurrences(Time.now + 4 * 60, Time.now + 16 * 60) expect(h[j0][0]).to be_within_1s_of(Time.now + 10 * 60) expect(h[j0][1]).to be_within_1s_of(Time.now + 15 * 60) end it 'respects :times for repeat jobs' do j0 = @scheduler.schedule_every '1m', :times => 10 do; end t0 = Time.parse((Time.now + 5 * 60).strftime('%Y-%m-%d %H:%M:01')) t1 = t0 + 12 * 60 - 1 h = @scheduler.occurrences(t0, t1) expect(h[j0].size).to eq(6) end end describe '#timeline' do it 'returns a [ [ time, job ], ... ] of job occurrences' do j0 = @scheduler.schedule_in '5m' do; end j1 = @scheduler.schedule_in '10m' do; end a = @scheduler.timeline(Time.now + 4 * 60, Time.now + 11 * 60) expect(a[0][0]).to be_within_1s_of(Time.now + 5 * 60) expect(a[0][1]).to eq(j0) expect(a[1][0]).to be_within_1s_of(Time.now + 10 * 60) expect(a[1][1]).to eq(j1) end it 'should not lock when running timeline with a :first_at specified' do now = Time.now # scheduling a cron job with a first_at and running #timeline used # to result in an infinite loop. @scheduler.cron('* * * * * *', :first_at => now + 3) {} jobs = @scheduler.timeline(now, now + 4) expect(jobs.size).to be 2 expect(jobs[0][0]).to be_within_1s_of now + 3 expect(jobs[1][0]).to be_within_1s_of now + 4 end end #-- # management methods #++ describe '#shutdown' do it 'blanks the uptime' do @scheduler.shutdown expect(@scheduler.uptime).to eq(nil) end it 'shuts the scheduler down' do @scheduler.shutdown sleep 0.100 sleep 0.400 if RUBY_VERSION < '1.9.0' t = Thread.list.find { |t| t[:name] == "rufus_scheduler_#{@scheduler.object_id}" } expect(t).to eq(nil) end it 'has a #stop alias' do @scheduler.stop expect(@scheduler.uptime).to eq(nil) end #it 'has a #close alias' end describe '#shutdown(:wait)' do it 'shuts down and blocks until all the jobs ended their current runs' do counter = 0 @scheduler.in '0s' do sleep 1 counter = counter + 1 end sleep 0.4 @scheduler.shutdown(:wait) expect(counter).to eq(1) expect(@scheduler.uptime).to eq(nil) expect(@scheduler.running_jobs).to eq([]) expect(@scheduler.threads).to eq([]) end end describe '#shutdown(:kill)' do it 'kills all the jobs and then shuts down' do counter = 0 @scheduler.in '0s' do sleep 1 counter = counter + 1 end @scheduler.at Time.now + 0.3 do sleep 1 counter = counter + 1 end sleep 0.4 @scheduler.shutdown(:kill) sleep 1.4 expect(counter).to eq(0) expect(@scheduler.uptime).to eq(nil) expect(@scheduler.running_jobs).to eq([]) expect(@scheduler.threads).to eq([]) end end describe '#pause' do it 'pauses the scheduler' do job = @scheduler.schedule_in '1s' do; end @scheduler.pause sleep(3) expect(job.last_time).to eq(nil) end end describe '#resume' do it 'works' do job = @scheduler.schedule_in '2s' do; end @scheduler.pause sleep(1) @scheduler.resume sleep(2) expect(job.last_time).not_to eq(nil) end end describe '#paused?' do it 'returns true if the scheduler is paused' do @scheduler.pause expect(@scheduler.paused?).to eq(true) end it 'returns false if the scheduler is not paused' do expect(@scheduler.paused?).to eq(false) @scheduler.pause @scheduler.resume expect(@scheduler.paused?).to eq(false) end end describe '#down?' do it 'returns true when the scheduler is down' do @scheduler.shutdown expect(@scheduler.down?).to eq(true) end it 'returns false when the scheduler is up' do expect(@scheduler.down?).to eq(false) end end describe '#up?' do it 'returns true when the scheduler is up' do expect(@scheduler.up?).to eq(true) end end #-- # job methods #++ describe '#jobs' do it 'is empty at the beginning' do expect(@scheduler.jobs).to eq([]) end it 'returns the list of scheduled jobs' do @scheduler.in '10d' do; end @scheduler.in '1w' do; end sleep(1) jobs = @scheduler.jobs expect(jobs.collect { |j| j.original }.sort).to eq(%w[ 10d 1w ]) end it 'returns all the jobs (even those pending reschedule)' do @scheduler.in '0s', :blocking => true do sleep 2 end sleep 0.4 expect(@scheduler.jobs.size).to eq(1) end it 'does not return unscheduled jobs' do job = @scheduler.schedule_in '0s', :blocking => true do sleep 2 end sleep 0.4 job.unschedule expect(@scheduler.jobs.size).to eq(0) end end describe '#jobs(:tag / :tags => x)' do it 'returns [] when there are no jobs with the corresponding tag' do expect(@scheduler.jobs(:tag => 'nada')).to eq([]) expect(@scheduler.jobs(:tags => %w[ nada hello ])).to eq([]) end it 'returns the jobs with the corresponding tag' do @scheduler.in '10d', :tag => 't0' do; end @scheduler.every '2h', :tag => %w[ t0 t1 ] do; end @scheduler.every '3h' do; end expect(@scheduler.jobs(:tags => 't0').map(&:original).sort).to eq( %w[ 10d 2h ] ) expect(@scheduler.jobs(:tags => 't1').map(&:original).sort).to eq( %w[ 2h ] ) expect(@scheduler.jobs(:tags => [ 't1', 't0' ]).map(&:original).sort).to eq( %w[ 2h ] ) end end describe '#every_jobs' do it 'returns EveryJob instances' do @scheduler.at '2030/12/12 12:10:00' do; end @scheduler.in '10d' do; end @scheduler.every '5m' do; end jobs = @scheduler.every_jobs expect(jobs.collect { |j| j.original }.sort).to eq(%w[ 5m ]) end end describe '#at_jobs' do it 'returns AtJob instances' do @scheduler.at '2030/12/12 12:10:00' do; end @scheduler.in '10d' do; end @scheduler.every '5m' do; end jobs = @scheduler.at_jobs expect(jobs.collect { |j| j.original }.sort).to eq([ '2030/12/12 12:10:00' ]) end end describe '#in_jobs' do it 'returns InJob instances' do @scheduler.at '2030/12/12 12:10:00' do; end @scheduler.in '10d' do; end @scheduler.every '5m' do; end jobs = @scheduler.in_jobs expect(jobs.collect { |j| j.original }.sort).to eq(%w[ 10d ]) end end describe '#cron_jobs' do it 'returns CronJob instances' do @scheduler.at '2030/12/12 12:10:00' do; end @scheduler.in '10d' do; end @scheduler.every '5m' do; end @scheduler.cron '* * * * *' do; end jobs = @scheduler.cron_jobs expect(jobs.collect { |j| j.original }.sort).to eq([ '* * * * *' ]) end end describe '#interval_jobs' do it 'returns IntervalJob instances' do @scheduler.at '2030/12/12 12:10:00' do; end @scheduler.in '10d' do; end @scheduler.every '5m' do; end @scheduler.cron '* * * * *' do; end @scheduler.interval '7m' do; end jobs = @scheduler.interval_jobs expect(jobs.collect { |j| j.original }.sort).to eq(%w[ 7m ]) end end #-- # callbacks #++ describe '#on_pre_trigger' do it 'is called right before a job triggers' do $out = [] def @scheduler.on_pre_trigger(job) $out << "pre #{job.id}" end job_id = @scheduler.in '0.5s' do |job| $out << job.id end sleep 0.7 expect($out).to eq([ "pre #{job_id}", job_id ]) end it 'accepts the job and the triggerTime as argument' do $tt = nil def @scheduler.on_pre_trigger(job, trigger_time) $tt = trigger_time end start = Time.now @scheduler.in '0.5s' do; end sleep 0.7 expect($tt.class).to eq(Time) expect($tt).to be > start expect($tt).to be < Time.now end context 'when it returns false' do it 'prevents the job from triggering' do $out = [] def @scheduler.on_pre_trigger(job) $out << "pre #{job.id}" false end job_id = @scheduler.in '0.5s' do |job| $out << job.id end sleep 0.7 expect($out).to eq([ "pre #{job_id}" ]) end end end describe '#on_post_trigger' do it 'is called right after a job triggers' do $out = [] def @scheduler.on_post_trigger(job) $out << "post #{job.id}" end job_id = @scheduler.in '0.5s' do |job| $out << job.id end sleep 0.7 expect($out).to eq([ job_id, "post #{job_id}" ]) end end #-- # misc #++ describe '.singleton / .s' do before(:each) do Rufus::Scheduler.class_eval { @singleton = nil } # ;-) end it 'returns a singleton instance of the scheduler' do s0 = Rufus::Scheduler.singleton s1 = Rufus::Scheduler.s expect(s0.class).to eq(Rufus::Scheduler) expect(s1.object_id).to eq(s0.object_id) end it 'accepts initialization parameters' do s = Rufus::Scheduler.singleton(:max_work_threads => 77) s = Rufus::Scheduler.singleton(:max_work_threads => 42) expect(s.max_work_threads).to eq(77) end end end rufus-scheduler-3.1.10/spec/spec_helper.rb000066400000000000000000000033251262271731200204720ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'pp' puts "RUBY_VERSION: #{RUBY_VERSION}" puts "RUBY_PLATFORM: #{RUBY_PLATFORM}" Thread.abort_on_exception = true require 'stringio' require 'rufus-scheduler' # # misc helper methods def ruby18? !! RUBY_VERSION.match(/^1\.8\./) end def jruby? !! RUBY_PLATFORM.match(/java/) end def local(*args) Time.local(*args) end alias lo local def utc(*args) Time.utc(*args) end def ltz(tz, *args) in_zone(tz) { Time.local(*args) } end def ltu(tz, *args) in_zone(tz) { Time.local(*args) }.getutc end def sleep_until_next_minute min = Time.now.min while Time.now.min == min; sleep 2; end end def sleep_until_next_second sec = Time.now.sec while Time.now.sec == sec; sleep 0.2; end end def in_zone(zone_name, &block) prev_tz = ENV['TZ'] ENV['TZ'] = zone_name block.call ensure ENV['TZ'] = prev_tz end def with_chronic(&block) require 'chronic' Object.const_set(:Khronic, Chronic) unless defined?(Khronic) Object.const_set(:Chronic, Khronic) unless defined?(Chronic) block.call ensure Object.send(:remove_const, :Chronic) end def without_chronic(&block) # for quick counter-tests ;-) block.call end # # matchers #require 'rspec/expectations' RSpec::Matchers.define :be_within_1s_of do |expected| match do |actual| if actual.respond_to?(:asctime) (actual.to_f - expected.to_f).abs <= 1.0 else false end end failure_message do |actual| if actual.respond_to?(:asctime) "expected #{actual.inspect} to be within 1 second of #{expected}" else "expected Time instance, got a #{actual.inspect}" end end end # # configure #RSpec.configure do |config| #end rufus-scheduler-3.1.10/spec/threads_spec.rb000066400000000000000000000033101262271731200206370ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Thu Jul 25 05:53:51 JST 2013 # require 'spec_helper' describe Rufus::Scheduler do before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end context 'thread pool' do it 'starts with an empty thread pool' do expect(@scheduler.work_threads.size).to eq(0) end it 'does not cross the max_work_threads threshold' do #@scheduler.min_work_threads = 2 @scheduler.max_work_threads = 5 10.times do @scheduler.in '0s' do sleep 5 end end sleep 0.5 #@scheduler.job_threads.each do |t| # p t.keys # p t[:rufus_scheduler_job].class #end expect(@scheduler.work_threads.size).to eq(5) end it 'does not cross the max_work_threads threshold (overlap: false)' do #@scheduler.min_work_threads = 2 @scheduler.max_work_threads = 5 10.times do @scheduler.in '0s', :overlap => false do sleep 5 end end sleep 0.5 #@scheduler.job_threads.each do |t| # p t.keys # p t[:rufus_scheduler_job].class #end expect(@scheduler.work_threads.size).to eq(5) end it 'does not execute unscheduled jobs' do @scheduler.max_work_threads = 1 counter = 0 job0 = @scheduler.schedule_in '0.3s' do counter += 1 sleep 1 end job1 = @scheduler.schedule_in '0.35s' do counter += 1 sleep 1 end sleep(0.1) while counter < 1 sleep(0.1) while @scheduler.work_queue.size < 1 job1.unschedule sleep(2) expect(counter).to eq(1) end end end rufus-scheduler-3.1.10/spec/zotime_spec.rb000066400000000000000000000243771262271731200205340ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Mar 11 21:17:36 JST 2015, quatre ans... # require 'spec_helper' describe Rufus::Scheduler::ZoTime do describe '.new' do it 'accepts an integer' do zt = Rufus::Scheduler::ZoTime.new(1234567890, 'America/Los_Angeles') expect(zt.seconds.to_i).to eq(1234567890) end it 'accepts a float' do zt = Rufus::Scheduler::ZoTime.new(1234567890.1234, 'America/Los_Angeles') expect(zt.seconds.to_i).to eq(1234567890) end it 'accepts a Time instance' do zt = Rufus::Scheduler::ZoTime.new( Time.utc(2007, 11, 1, 15, 25, 0), 'America/Los_Angeles') expect(zt.seconds.to_i).to eq(1193930700) end end #it "flips burgers" do # puts "---" # t0 = ltz('America/New_York', 2004, 10, 31, 0, 30, 0) # t1 = ltz('America/New_York', 2004, 10, 31, 1, 30, 0) # p t0 # p t1 # puts "---" # zt0 = Rufus::Scheduler::ZoTime.new(t0, 'America/New_York') # zt1 = Rufus::Scheduler::ZoTime.new(t1, 'America/New_York') # p zt0.time # p zt1.time # puts "---" # zt0.add(3600) # p [ zt0.time, zt0.time.zone ] # p [ zt1.time, zt1.time.zone ] # #puts "---" # #zt0.add(3600) # #zt1.add(3600) # #p [ zt0.time, zt0.time.zone ] # #p [ zt1.time, zt1.time.zone ] #end describe '#time' do it 'returns a Time instance in with the right offset' do zt = Rufus::Scheduler::ZoTime.new(1193898300, 'America/Los_Angeles') t = zt.time expect(t.strftime('%Y/%m/%d %H:%M:%S %Z') ).to eq('2007/10/31 23:25:00 PDT') end # New York EST: UTC-5 # summer (dst) EDT: UTC-4 it 'chooses the DST time when there is ambiguity' do t = ltz('America/New_York', 2004, 10, 31, 0, 30, 0) zt = Rufus::Scheduler::ZoTime.new(t, 'America/New_York') zt.add(3600) ztt = zt.time expect(ztt.to_i).to eq(1099204200 - 3600) expect(ztt.strftime('%Y/%m/%d %H:%M:%S %Z %z') ).to eq('2004/10/31 01:30:00 EDT -0400') end end describe '#utc' do it 'returns an UTC Time instance' do zt = Rufus::Scheduler::ZoTime.new(1193898300, 'America/Los_Angeles') t = zt.utc expect(t.to_i).to eq(1193898300) if ruby18? expect(t.strftime('%Y/%m/%d %H:%M:%S %Z %z') ).to eq('2007/11/01 06:25:00 GMT +0000') else expect(t.strftime('%Y/%m/%d %H:%M:%S %Z %z') ).to eq('2007/11/01 06:25:00 UTC +0000') end end end describe '#add' do it 'adds seconds' do zt = Rufus::Scheduler::ZoTime.new(1193898300, 'Europe/Paris') zt.add(111) expect(zt.seconds).to eq(1193898300 + 111) end it 'goes into DST' do zt = Rufus::Scheduler::ZoTime.new( Time.gm(2015, 3, 8, 9, 59, 59), 'America/Los_Angeles') t0 = zt.time zt.add(1) t1 = zt.time st0 = t0.strftime('%Y/%m/%d %H:%M:%S %Z') + " #{t0.isdst}" st1 = t1.strftime('%Y/%m/%d %H:%M:%S %Z') + " #{t1.isdst}" expect(t0.to_i).to eq(1425808799) expect(t1.to_i).to eq(1425808800) expect(st0).to eq('2015/03/08 01:59:59 PST false') expect(st1).to eq('2015/03/08 03:00:00 PDT true') end it 'goes out of DST' do zt = Rufus::Scheduler::ZoTime.new( ltz('Europe/Berlin', 2014, 10, 26, 01, 59, 59), 'Europe/Berlin') t0 = zt.time zt.add(1) t1 = zt.time zt.add(3600) t2 = zt.time zt.add(1) t3 = zt.time st0 = t0.strftime('%Y/%m/%d %H:%M:%S %Z') + " #{t0.isdst}" st1 = t1.strftime('%Y/%m/%d %H:%M:%S %Z') + " #{t1.isdst}" st2 = t2.strftime('%Y/%m/%d %H:%M:%S %Z') + " #{t2.isdst}" st3 = t3.strftime('%Y/%m/%d %H:%M:%S %Z') + " #{t3.isdst}" expect(t0.to_i).to eq(1414281599) expect(t1.to_i).to eq(1414285200 - 3600) expect(t2.to_i).to eq(1414285200) expect(t3.to_i).to eq(1414285201) expect(st0).to eq('2014/10/26 01:59:59 CEST true') expect(st1).to eq('2014/10/26 02:00:00 CEST true') expect(st2).to eq('2014/10/26 02:00:00 CET false') expect(st3).to eq('2014/10/26 02:00:01 CET false') expect(t1 - t0).to eq(1) expect(t2 - t1).to eq(3600) expect(t3 - t2).to eq(1) end end describe '#to_f' do it 'returns the @seconds' do zt = Rufus::Scheduler::ZoTime.new(1193898300, 'Europe/Paris') expect(zt.to_f).to eq(1193898300) end end describe '.envtzable?' do def etza?(s); Rufus::Scheduler::ZoTime.envtzable?(s); end it 'matches' do expect(etza?('Asia/Tokyo')).to eq(true) expect(etza?('America/Los_Angeles')).to eq(true) expect(etza?('Europe/Paris')).to eq(true) expect(etza?('UTC')).to eq(true) expect(etza?('Japan')).to eq(true) expect(etza?('Turkey')).to eq(true) end it 'does not match' do expect(etza?('14:00')).to eq(false) expect(etza?('14:00:14')).to eq(false) expect(etza?('2014/12/11')).to eq(false) expect(etza?('2014-12-11')).to eq(false) expect(etza?('+25:00')).to eq(false) expect(etza?('+09:00')).to eq(false) expect(etza?('-01:30')).to eq(false) expect(etza?('-0200')).to eq(false) expect(etza?('Wed')).to eq(false) expect(etza?('Sun')).to eq(false) expect(etza?('Nov')).to eq(false) expect(etza?('PST')).to eq(false) expect(etza?('Z')).to eq(false) expect(etza?('YTC')).to eq(false) expect(etza?('Asia/Paris')).to eq(false) expect(etza?('Nada/Nada')).to eq(false) end #it 'returns true for all entries in the tzinfo list' do # File.readlines( # File.join(File.dirname(__FILE__), '../misc/tz_all.txt') # ).each do |tz| # tz = tz.strip # if tz.length > 0 && tz.match(/^[^#]/) # p tz # expect(llat?(tz)).to eq(true) # end # end #end end describe '.is_timezone?' do def is_timezone?(o); Rufus::Scheduler::ZoTime.is_timezone?(o); end it 'returns true when passed a string describing a timezone' do expect(is_timezone?('Asia/Tokyo')).to eq(true) expect(is_timezone?('Europe/Paris')).to eq(true) expect(is_timezone?('UTC')).to eq(true) expect(is_timezone?('GMT')).to eq(true) expect(is_timezone?('Z')).to eq(true) expect(is_timezone?('Zulu')).to eq(true) expect(is_timezone?('PST')).to eq(true) expect(is_timezone?('+09:00')).to eq(true) expect(is_timezone?('-01:30')).to eq(true) expect(is_timezone?('Japan')).to eq(true) expect(is_timezone?('Turkey')).to eq(true) end it 'returns false when it cannot make sense of the timezone' do expect(is_timezone?('Asia/Paris')).to eq(false) #expect(is_timezone?('YTC')).to eq(false) expect(is_timezone?('Nada/Nada')).to eq(false) expect(is_timezone?('7')).to eq(false) expect(is_timezone?('06')).to eq(false) expect(is_timezone?('sun#3')).to eq(false) end #it 'returns true for all entries in the tzinfo list' do # File.readlines( # File.join(File.dirname(__FILE__), '../misc/tz_all.txt') # ).each do |tz| # tz = tz.strip # if tz.length > 0 && tz.match(/^[^#]/) # #p tz # expect(is_timezone?(tz)).to eq(true) # end # end #end end describe '.parse' do it 'parses a time string without a timezone' do zt = in_zone('Europe/Moscow') { Rufus::Scheduler::ZoTime.parse('2015/03/08 01:59:59') } t = zt.time u = zt.utc expect(t.to_i).to eq(1425769199) expect(u.to_i).to eq(1425769199) expect(t.strftime('%Y/%m/%d %H:%M:%S %Z %z') + " #{t.isdst}" ).to eq('2015/03/08 01:59:59 MSK +0300 false') if ruby18? expect(u.strftime('%Y/%m/%d %H:%M:%S %Z %z') + " #{u.isdst}" ).to eq('2015/03/07 22:59:59 GMT +0000 false') else expect(u.strftime('%Y/%m/%d %H:%M:%S %Z %z') + " #{u.isdst}" ).to eq('2015/03/07 22:59:59 UTC +0000 false') end end it 'parses a time string with a full name timezone' do zt = Rufus::Scheduler::ZoTime.parse( '2015/03/08 01:59:59 America/Los_Angeles') t = zt.time u = zt.utc expect(t.to_i).to eq(1425808799) expect(u.to_i).to eq(1425808799) expect(t.strftime('%Y/%m/%d %H:%M:%S %Z %z') + " #{t.isdst}" ).to eq('2015/03/08 01:59:59 PST -0800 false') if ruby18? expect(u.strftime('%Y/%m/%d %H:%M:%S %Z %z') + " #{u.isdst}" ).to eq('2015/03/08 09:59:59 GMT +0000 false') else expect(u.strftime('%Y/%m/%d %H:%M:%S %Z %z') + " #{u.isdst}" ).to eq('2015/03/08 09:59:59 UTC +0000 false') end end it 'parses a time string with a delta timezone' do zt = in_zone('Europe/Berlin') { Rufus::Scheduler::ZoTime.parse('2015-12-13 12:30 -0200') } t = zt.time u = zt.utc expect(t.to_i).to eq(1450017000) expect(u.to_i).to eq(1450017000) expect(t.strftime('%Y/%m/%d %H:%M:%S %Z %z') + " #{t.isdst}" ).to eq('2015/12/13 15:30:00 CET +0100 false') if ruby18? expect(u.strftime('%Y/%m/%d %H:%M:%S %Z %z') + " #{u.isdst}" ).to eq('2015/12/13 14:30:00 GMT +0000 false') else expect(u.strftime('%Y/%m/%d %H:%M:%S %Z %z') + " #{u.isdst}" ).to eq('2015/12/13 14:30:00 UTC +0000 false') end end it 'parses a time string with a delta (:) timezone' do zt = in_zone('Europe/Berlin') { Rufus::Scheduler::ZoTime.parse('2015-12-13 12:30 -02:00') } t = zt.time u = zt.utc expect(t.to_i).to eq(1450017000) expect(u.to_i).to eq(1450017000) expect(t.strftime('%Y/%m/%d %H:%M:%S %Z %z') + " #{t.isdst}" ).to eq('2015/12/13 15:30:00 CET +0100 false') if ruby18? expect(u.strftime('%Y/%m/%d %H:%M:%S %Z %z') + " #{u.isdst}" ).to eq('2015/12/13 14:30:00 GMT +0000 false') else expect(u.strftime('%Y/%m/%d %H:%M:%S %Z %z') + " #{u.isdst}" ).to eq('2015/12/13 14:30:00 UTC +0000 false') end end it 'takes the local TZ when it does not know the timezone' do in_zone 'Europe/Moscow' do zt = Rufus::Scheduler::ZoTime.parse('2015/03/08 01:59:59 Nada/Nada') expect(zt.time.zone).to eq('MSK') end end end end