pax_global_header00006660000000000000000000000064140734246050014517gustar00rootroot0000000000000052 comment=e79d068d3e69a9f9966b376f652a8564f0c11364 rufus-scheduler-3.8.0/000077500000000000000000000000001407342460500146475ustar00rootroot00000000000000rufus-scheduler-3.8.0/.github/000077500000000000000000000000001407342460500162075ustar00rootroot00000000000000rufus-scheduler-3.8.0/.github/workflows/000077500000000000000000000000001407342460500202445ustar00rootroot00000000000000rufus-scheduler-3.8.0/.github/workflows/test.yaml000066400000000000000000000014741407342460500221150ustar00rootroot00000000000000 name: test on: [ push, pull_request ] jobs: test: if: " ! (contains(github.event.head_commit.message, 'skip ci') || contains(github.event.head_commit.message, 'ci skip'))" name: ${{matrix.ruby}} on ${{matrix.os}} strategy: matrix: os: [ ubuntu-latest ] ruby: [ '2.3', '2.5', '2.6', '2.7', '3.0', jruby-9.2 ] experimental: [ false ] fail-fast: false runs-on: ${{matrix.os}} continue-on-error: ${{matrix.experimental}} steps: - uses: actions/checkout@v2 - uses: ruby/setup-ruby@v1 with: ruby-version: ${{matrix.ruby}} bundler-cache: true - run: ruby --version - run: gem --version - run: bundle --version - run: bundle install - run: bundle exec rspec --force-color --format documentation rufus-scheduler-3.8.0/.gitignore000066400000000000000000000002171407342460500166370ustar00rootroot00000000000000 *.swp .vimrc .viminfo .vimgrep .vimspec pkg/ .ruby-version #.rspec .errors .rspec.out .bxsinfo.yaml .bxsenvs.yaml .todo.md Gemfile.lock rufus-scheduler-3.8.0/.rspec000066400000000000000000000000401407342460500157560ustar00rootroot00000000000000--colour --format documentation rufus-scheduler-3.8.0/.travis.yml000066400000000000000000000007341407342460500167640ustar00rootroot00000000000000 language: ruby rvm: #- 1.8.7 # over from rufus-scheduler 3.4.0 #- 1.9.2 - 1.9.3 #- 2.0.0 #- 2.1.1 #- 2.2.3 - 2.3.3 - 2.4.6 - 2.5.5 - 2.6.6 - 2.7.1 #- jruby-9.1.13.0 - jruby-9.2.14.0 #matrix: # include: # - rvm: jruby-9.1.13.0 # #- env: JRUBY_OPTS="--profile.api" #before_install: gem install bundler script: bundle exec rspec branches: only: - master #except: # - master cache: bundler #env: # - WHATEVER_DEFAULT_TIMEOUT=7 rufus-scheduler-3.8.0/CHANGELOG.md000066400000000000000000000254341407342460500164700ustar00rootroot00000000000000 # CHANGELOG.md ### rufus-scheduler 3.8.0 - released 2021-07-14 * Add #source_location to Job, gh-322 ### rufus-scheduler 3.7.0 - released 2020-12-31 * Implement Job name:/n: #name and #name=, gh-309 * Add Job #has_key?, #value, and #entries * Add #locals access to Job * Implement Scheduler#around_trigger, @jjb, gh-310 * Accept max_worker_threads: for max_work_threads: * Clean up Scheduler#shutdwon, thanks @itsaphel and @jjb, gh-304, gh-315 * f59df40 Bring in discard_past: for every jobs, gh-290 * 7613277 Introduce :discard_past = false for cron, gh-305 ### rufus-scheduler 3.6.0 - released 2019-04-22 * Let Scheduler#cron fail if the cron string is invalid, gh-289 * Implement Job#next_times(count) for cron, every, and interval jobs * Implement Job#next_times(count) for at and in jobs * Stop fooling around and stick to https://semver.org ### rufus-scheduler 3.5.2 - released 2018-08-01 * Use Fugit::Cron#rough_frequency * Improve Job#check_frequency performance, gh-276, @drcapulet ### rufus-scheduler 3.5.1 - released 2018-07-20 * Upgrade fugit to 1.1.4 (with out of DST issue fix) * Ensure JRuby doesn't count fresh, new, work threads as vacant ### rufus-scheduler 3.5.0 - released 2018-05-15 * Use fugit to parse durations * Drop .parse_time_string and .parse_duration_string * Use fugit to parse cronlines ### rufus-scheduler 3.4.2 - released 2017-05-24 (had yanked 3.4.1, going 3.4.2) ### rufus-scheduler 3.4.1 - released 2017-05-24 * Let #schedule accept a CronLine instance, gh-247 ### rufus-scheduler 3.4.0 - released 2017-03-23 * Stop supporting Ruby < 1.9 * Drop ZoTime for et-orbi Etorbi::EoTime, gh-240 * Fix for ZooKeeper example, thanks to @djrodgerspryor, gh-238 ### rufus-scheduler 3.3.4 - released 2017-02-16 * More detailed "cannot determine timezone from nil" message, gh-237 ### rufus-scheduler 3.3.3 - released 2017-01-29 * use Rails' timezone by default if Rails is present, gh-230, gh-233, thanks Alexander Deeb * is_a?(Fixnum) replaced by is_a?(Integer), gh-232, thanks Cody Cutrer * Fix for every double trigger, gh-231, thanks Sofia Bravo ### rufus-scheduler 3.3.2 - released 2017-01-05 * Fix ZoTime issue with `Time.zone.now #=> 'CST'`, thanks zzjin * Fix cron weekdays + monthdays, by Dominik Sander, https://github.com/dsander * Speedup CronLine#brute_frequency, by Dominik Sander * Use object_id instead of hash to make Job id ### rufus-scheduler 3.3.1 - released 2016-12-03 * gh-222 fall back on `ENV['TZ']` when Time.now.zone is something like "中国标准时间" (ask for "Asia/Shanghai"), thanks to https://github.com/lovingyu ### rufus-scheduler 3.3.0 - released 2016-11-28 * Bring in Piavka's Job#trigger_off_schedule, gh-214 * Reject "day 0" in cronlines, thanks to Ramon Tayag, https://github.com/ramontayag * Move away from `ENV['TZ']`, thanks to Akinori Musha, https://github.com/knu * Fix .parse_to_time vs Date issue, as reported by @nsatragno ### rufus-scheduler 3.2.2 - released 2016-08-14 * job opt hash preservation, as suggested in gh-212, by https://github.com/d-m-u * introduce Job#previous_time * countered ActiveRecord 3.2.22 on gh-210, by https://github.com/paulodelgado ### rufus-scheduler 3.2.1 - released 2016-05-04 * accept `'* * * * 5L'` (last friday) (equivalent to `'* * * * 5#-1'`) * CronLine#to_a (#to_array aliasing to it) * simplify .parse_duration (and trim input) * raise on `"*/0 * * * *"`, by https://github.com/simook * introduce "days to end of month" in cron strings ### rufus-scheduler 3.2.0 - released 2015-12-28 * cache CronLine#brute_frequency results, gh-188 and gh-89 * "every" shift prevention by https://github.com/Korrigan * Ruby warnings silenced by https://github.com/vivitar ### 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]` being 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](https://rubygems.org/gems/openwferu-scheduler/versions) before that) rufus-scheduler-3.8.0/CREDITS.md000066400000000000000000000177021407342460500162750ustar00rootroot00000000000000 # CREDITS.md ## Contributors * John Bachir https://github.com/jjb gh-310 * Daniel Berger https://github.com/djberg96 gh-300 * Ceyhun Onur https://github.com/ceyonur parse_cron no_error: true * Darwin Wu https://github.com/dwaxe Rails initializer vs tests change * Mike Karolow https://github.com/mike-yesware update Travis target Rubies * Jack-Nie https://github.com/jack-nie gh-285 fix broken comment link * Yechiel Kalmenson (https://github.com/achasveachas) README link fix * Alex Coomans (https://github.com/drcapulet) gh-276 freq check pref improvement * Vais Salikhov (https://github.com/vais) many document clarifications * Wes McNamee (https://github.com/ghostsquad) let #schedule accept a CronLine * Joe Rafaniello (https://github.com/jrafanie) Travis Ruby 2.4.1 * Benjamin Fleischer (https://github.com/bf4) ZoTime#subtract * Sam Rowe (https://github.com/riddley) gh-240 timezone for Debian * Daniel Rodgers-Pryor (https://github.com/djrodgerspryor), gh-238 fix ZooKeeper example * Cody Cutrer (https://github.com/ccutrer) gh-232 is_a?(Fixnum) replacement * Dominik Sander (https://github.com/dsander), gh-225, gh-226 * Piavka (https://github.com/piavka) Job#trigger_off_schedule, gh-214 * Paulo Delgado (https://github.com/paulodelgado) counter ActiveRecord, gh-210 * Anjali Sharma (https://github.com/anjali-sharma) enhance job#last_time example * Kyle Simukka (https://github.com/simook) raise on `"*/0 * * * *"` * Ryan McGeary (https://github.com/rmm5t) svg badges for the readme * Balasankar C (https://github.com/balasankarc) fix CronJob spec vs December * Matthieu Rosinski (https://github.com/Korrigan) prevent "every" shifts * vivitar (https://github.com/vivitar) silenced a set of Ruby warnings * 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 (https://github.com/chrisk) rspec 2.0 refinements * Tanzeeb Khalili (https://github.com/tanzeeb) cron and timezones * Adam Davies (https://github.com/adz) `:allow_overlapping => false` * Klaas Jan Wierenga (https://github.com/kjwierenga) at/every/in stress tests (1.0 and 2.0) * TobyH (https://github.com/tobyh) faster and cleaner `CronLine#next_time` ## Feedback * aphel (https://github.com/itsaphel) #shutdown vs current thread, gh-304 * aesyondu (https://github.com/aesyondu) Rails console 4.2.x, gh-186 * Sasha Hoellger (https://github.com/mitnal) parse_cron and readme, gh-270 * Gian (https://github.com/snmgian) cron vs :first clarification, gh-266 * Vito Laurenza (https://github.com/veetow) help debugging tz issues, gh-240 * Yoshimi Keiji (https://github.com/walf443) v.3.3.3 mislabelling * Alexander Deeb (https://github.com/adeeb1) gh-230 * Sofia Bravo (http://stackoverflow.com/users/1123850/sofia-bravo) gh-231 * zzjin (https://github.com/zzjin) 3.3.x vs CST abbreviated timezone, gh-228 * lovingyu (https://github.com/lovingyu) fallback to `ENV['TZ']`, gh-222 * Ramon Tayag (https://github.com/ramontayag) prevent day 0 in cronlines * Akinori Musha (https://github.com/knu) `ENV['TZ']` setting is harmful * Nicolás Satragno (https://twitter.com/nsatragno) parse_to_time vs Date * d-m-u duhlmann (https://github.com/d-m-u) job opt hash preservation * Anjali Sharma (https://github.com/anjali-sharma) fix typographical error * Jonathan Campos (https://github.com/jonbcampos) negative cron day idea * Andrey Morskov (https://github.com/accessd) fix typographical error * Eduardo Maia (https://github.com/emaiax) rufus and the Rails console * 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 * Adefila (https://twitter.com/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 * Joast (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 (https://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 (dead) ## and finally * Many thanks to the contributors of fugit (https://github.com/floraison/fugit) and et-orbi (https://github.com/floraison/et-orbi) * 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.8.0/Gemfile000066400000000000000000000005701407342460500161440ustar00rootroot00000000000000 source 'https://rubygems.org' #gem 'tzinfo-data' #gem 'et-orbi', path: '../et-orbi/' # temporarily #gem 'et-orbi', git: 'https://github.com/floraison/et-orbi.git' # temporarily # #gem 'fugit', path: '../fugit/' # temporarily #gem 'fugit', git: 'https://github.com/floraison/fugit.git' # temporarily # # temporary, development redirections #gem 'ruby-prof' gemspec rufus-scheduler-3.8.0/LICENSE.txt000066400000000000000000000020761407342460500164770ustar00rootroot00000000000000 Copyright (c) 2005-2021, 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.8.0/Makefile000066400000000000000000000014111407342460500163040ustar00rootroot00000000000000 NAME = \ $(shell ruby -e "s = eval(File.read(Dir['*.gemspec'][0])); puts s.name") VERSION = \ $(shell ruby -e "s = eval(File.read(Dir['*.gemspec'][0])); puts s.version") count_lines: find lib -name "*.rb" | xargs cat | ruby -e "p STDIN.readlines.count { |l| l = l.strip; l[0, 1] != '#' && l != '' }" find spec -name "*_spec.rb" | xargs cat | ruby -e "p STDIN.readlines.count { |l| l = l.strip; l[0, 1] != '#' && l != '' }" cl: count_lines gemspec_validate: @echo "---" ruby -e "s = eval(File.read(Dir['*.gemspec'].first)); p s.validate" @echo "---" name: gemspec_validate @echo "$(NAME) $(VERSION)" build: gemspec_validate gem build $(NAME).gemspec mkdir -p pkg mv $(NAME)-$(VERSION).gem pkg/ push: build gem push --otp "$(OTP)" pkg/$(NAME)-$(VERSION).gem rufus-scheduler-3.8.0/README.md000066400000000000000000001423601407342460500161340ustar00rootroot00000000000000 # rufus-scheduler [![tests](https://github.com/jmettraux/rufus-scheduler/workflows/test/badge.svg)](https://github.com/jmettraux/rufus-scheduler/actions) [![Gem Version](https://badge.fury.io/rb/rufus-scheduler.svg)](https://badge.fury.io/rb/rufus-scheduler) [![Join the chat at https://gitter.im/floraison/fugit](https://badges.gitter.im/floraison/fugit.svg)](https://gitter.im/floraison/fugit?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) Job scheduler for Ruby (at, cron, in and every jobs). It uses threads. **Note**: maybe are you looking for the [README of rufus-scheduler 2.x](https://github.com/jmettraux/rufus-scheduler/blob/two/README.rdoc)? (especially if you're using [Dashing](https://github.com/Shopify/dashing) which is [stuck](https://github.com/Shopify/dashing/blob/master/dashing.gemspec) on rufus-scheduler 2.0.24) Quickstart: ```ruby # quickstart.rb require 'rufus-scheduler' scheduler = Rufus::Scheduler.new scheduler.in '3s' do puts 'Hello... Rufus' end scheduler.join # # let the current thread join the scheduler thread # # (please note that this join should be removed when scheduling # in a web application (Rails and friends) initializer) ``` (run with `ruby quickstart.rb`) Various forms of scheduling are supported: ```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.every '3h10m' do # do something every 3 hours and 10 minutes end scheduler.cron '5 0 * * *' do # do something every day, five minutes after midnight # (see "man 5 crontab" in your terminal) end # ... ``` Rufus-scheduler uses [fugit](https://github.com/floraison/fugit) for parsing time strings, [et-orbi](https://github.com/floraison/et-orbi) for pairing time and [tzinfo](https://github.com/tzinfo/tzinfo) timezones. ## non-features Rufus-scheduler (out of the box) is an in-process, in-memory scheduler. It uses threads. It does not persist your schedules. When the process is gone and the scheduler instance with it, the schedules are gone. A rufus-scheduler instance will go on scheduling while it is present among the objects in a Ruby process. To make it stop scheduling you have to call its [`#shutdown` method](#schedulershutdown). ## related and similar gems * [Whenever](https://github.com/javan/whenever) - let cron call back your Ruby code, trusted and reliable cron drives your schedule * [ruby-clock](https://github.com/jjb/ruby-clock) - a clock process / job scheduler for Ruby * [Clockwork](https://github.com/Rykian/clockwork) - rufus-scheduler inspired gem * [Crono](https://github.com/plashchynski/crono) - an in-Rails cron scheduler * [PerfectSched](https://github.com/treasure-data/perfectsched) - highly available distributed cron built on [Sequel](https://sequel.jeremyevans.net) and more (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 with Ruby's ```sleep(100)``` * The scheduler isn't catching the whole of Exception anymore, only StandardError * The error_handler is [#on_error](#rufusscheduleron_errorjob-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", "please" and "thanks" are not swear words. Go read [how to report bugs effectively](https://www.chiark.greenend.org.uk/~sgtatham/bugs.html), twice. Update: [help_help.md](https://gist.github.com/jmettraux/310fed75f568fd731814) might help help you. ### on Gitter You can find help via chat over at [https://gitter.im/floraison/fugit](https://gitter.im/floraison/fugit). It's [fugit](https://github.com/floraison/fugit), [et-orbi](https://github.com/floraison/et-orbi), and rufus-scheduler combined chat room. Please be courteous. ### 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](https://stackoverflow.com/questions/ask?tags=rufus-scheduler+ruby) is better. ### faq * [It doesn't work...](https://www.chiark.greenend.org.uk/~sgtatham/bugs.html) * [I want a refund](https://blog.nodejitsu.com/getting-refunds-on-open-source-projects) * [Passenger and rufus-scheduler](https://stackoverflow.com/questions/18108719/debugging-rufus-scheduler/18156180#18156180) * [Passenger and rufus-scheduler (2)](https://stackoverflow.com/questions/21861387/rufus-cron-job-not-working-in-apache-passenger#answer-21868555) * [Passenger in-depth spawn methods](https://www.phusionpassenger.com/library/indepth/ruby/spawn_methods/) * [Passenger in-depth spawn methods (smart spawning)](https://www.phusionpassenger.com/library/indepth/ruby/spawn_methods/#smart-spawning-hooks) * [The scheduler comes up when running the Rails console or a Rake task](https://github.com/jmettraux/rufus-scheduler#avoid-scheduling-when-running-the-ruby-on-rails-console) * [The job triggers twice](https://github.com/jmettraux/rufus-scheduler#lockfile--mylockfiletxt) * [I don't get any of this, I just want it to work in my Rails application](#so-rails) * [I get "zotime.rb:41:in `initialize': cannot determine timezone from nil"](#i-get-zotimerb41in-initialize-cannot-determine-timezone-from-nil) ## 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 decides 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 here gives back an IntervalJob). ### schedule blocks arguments (job, time) A schedule block may be given 0, 1 or 2 arguments. The first argument is "job", it's simply the Job instance involved. It might be useful if the job is to be unscheduled for some reason. ```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 responds 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 ### name: string Sets the name of the job. ```ruby scheduler.cron '*/15 8 * * *', name: 'Robert' do |job| puts "A, it's #{Time.now} and my name is #{job.name}" end job1 = scheduler.schedule_cron '*/30 9 * * *', n: 'temporary' do |job| puts "B, it's #{Time.now} and my name is #{job.name}" end # ... job1.name = 'Beowulf' ``` ### blocking: true By default, jobs are triggered in their own, new threads. When `blocking: true`, the job is triggered in the scheduler thread (a new thread is not created). Yes, while a blocking job is running, the scheduler is not scheduling. ### overlap: false Since, by default, jobs are triggered in their own new threads, job instances might overlap. For example, a job that takes 10 minutes and is scheduled every 7 minutes will have overlaps. To prevent overlap, one can set `overlap: false`. Such a job will not trigger if one of its instances is already running. The `:overlap` option is considered before the `:mutex` option when the scheduler is reviewing jobs for triggering. ### mutex: mutex_instance / mutex_name / array of mutexes When a job with a mutex triggers, the job's block is executed with the mutex around it, preventing other jobs with the same mutex from entering (it makes the other jobs wait until it exits the mutex). This is different from `overlap: false`, which is, first, limited to instances of the same job, and, second, doesn't make the incoming job instance block/wait but give up. `:mutex` accepts a mutex instance or a mutex name (String). It also accept an array of mutex names / mutex instances. It allows for complex relations between jobs. Array of mutexes: original idea and implementation by [Rainux Luo](https://github.com/rainux) Note: creating lots of different mutexes is OK. Rufus-scheduler will place them in its Scheduler#mutexes hash... And they won't get garbage collected. The `:overlap` option is considered before the `:mutex` option when the scheduler is reviewing jobs for triggering. ### timeout: duration or point in time It's OK to specify a timeout when scheduling some work. After the time specified, it gets interrupted via a Rufus::Scheduler::TimeoutError. ```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 as well, the :first will point to the first time the job has to trigger, the following trigger times are then determined by the cron string. ```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 makes 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 occurrence 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 makes 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 returns 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 otherwise. ```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 # => # ``` ### source_location Added to rufus-scheduler 3.8.0. Returns the array `[ 'path/to/file.rb', 123 ]` like `Proc#source_location` does. ```ruby require 'rufus-scheduler' scheduler = Rufus::Scheduler.new job = scheduler.schedule_every('2h') { p Time.now } p job.source_location # ==> [ '/home/jmettraux/rufus-scheduler/test.rb', 6 ] ``` ### scheduled_at Returns the Time instance when the job got created. ```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). ```ruby job = scheduler.schedule_every('10s') do; end job.scheduled_at # => 2013-07-17 23:48:54 +0900 job.last_time # => nil (since we've just scheduled it) # after 10 seconds job.scheduled_at # => 2013-07-17 23:48:54 +0900 (same as above) job.last_time # => 2013-07-17 23:49:04 +0900 ``` ### previous_time Returns the previous `#next_time` ```ruby scheduler.every('10s') do |job| puts "job scheduled for #{job.previous_time} triggered at #{Time.now}" puts "next time will be around #{job.next_time}" puts "." end ``` ### last_work_time, mean_work_time The job keeps track of how long its work was in the `last_work_time` attribute. For a one time job (in, at) it's probably not very useful. The attribute `mean_work_time` contains a computed mean work time. It's recomputed after every run (if it's a repeat job). ### next_times(n) Returns an array of `EtOrbi::EoTime` instances (Time instances with a designated time zone), listing the `n` next occurrences for this job. Please note that for "interval" jobs, a mean work time is computed each time and it's used by this `#next_times(n)` method to approximate the next times beyond the immediate next time. ### unschedule Unschedule the job, preventing it from firing again and removing it from the schedule. This doesn't prevent a running thread for this job to run until its end. ### threads Returns the list of threads currently "hosting" runs of this Job instance. ### kill Interrupts all the work threads currently running for this job instance. They discard their work and are free for their next run (of whatever job). Note: this doesn't unschedule the Job instance. Note: if the job is pooled for another run, a free work thread will probably pick up that next run and the job will appear as running again. You'd have to unschedule and kill to make sure the job doesn't run again. ### running? Returns true if there is at least one running Thread hosting a run of this Job instance. ### scheduled? Returns true if the job is scheduled (is due to trigger). For repeat jobs it should return true until the job gets unscheduled. "at" and "in" jobs will respond with false as soon as they start running (execution triggered). ### pause, resume, paused?, paused_at These four methods are only available to CronJob, EveryJob and IntervalJob instances. One can pause or resume such jobs thanks to these methods. ```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?, has_key?, keys, values, and entries Threads have thread-local variables, similarly Rufus-scheduler jobs have job-local variables. Those are more like a dict with thread-safe access. ```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.has_key?(:timestamp) # => true job.keys # => [ :timestamp, :counter ] ``` Locals can be set at schedule time: ```ruby job0 = @scheduler.schedule_cron '*/15 12 * * *', locals: { a: 0 } do # ... end job1 = @scheduler.schedule_cron '*/15 13 * * *', l: { a: 1 } do # ... end ``` One can fetch the Hash directly with `Job#locals`. Of course, direct manipulation is not thread-safe. ```ruby job.locals.entries do |k, v| p "#{k}: #{v}" end ``` ### call Job instances have a #call method. It simply calls the scheduled block or callable immediately. ```ruby job = @scheduler.schedule_every '10m' do |job| # ... end job.call ``` Warning: the Scheduler[#on_error](#rufusscheduleron_errorjob-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 for time. ## EveryJob, IntervalJob and CronJob methods ### next_time Returns the next time the job will trigger (hopefully). ### count Returns how many times the job fired. ## EveryJob methods ### frequency It returns the scheduling frequency. For a job scheduled "every 20s", it's 20. It's used to determine if the job frequency is higher than the scheduler frequency (it raises an ArgumentError if that is the case). ## IntervalJob methods ### interval Returns the interval scheduled between each execution of the job. Every jobs use a time duration between each start of their execution, while interval jobs use a time duration between the end of an execution and the start of the next. ## CronJob methods ### brute_frequency An expensive method to run, it's brute. It caches its results. By default it runs for 2017 (a non leap-year). ``` require 'rufus-scheduler' Rufus::Scheduler.parse('* * * * *').brute_frequency # # => # # # Occurs 525600 times in a span of 1 year (2017) and 1 day. # There are least 60 seconds between "triggers" and at most 60 seconds. Rufus::Scheduler.parse('0 12 * * *').brute_frequency # => # Rufus::Scheduler.parse('0 12 * * *').brute_frequency.to_debug_s # => "dmin: 1D, dmax: 1D, ocs: 365, spn: 52W1D, spnys: 1, yocs: 365" # # 365 occurrences, at most 1 day between each, at least 1 day. ``` The `CronJob#frequency` method found in rufus-scheduler < 3.5 has been retired. ## looking up jobs ### Scheduler#job(job_id) The scheduler ```#job(job_id)``` method can be used to look up Job instances. ```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 look up 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(wait: n) Shuts down the scheduler, waits (blocks) at most n seconds until all the jobs cease running. (Jobs are killed after n seconds have elapsed). ### Scheduler#shutdown(:kill) Kills all the job (threads) and then shuts the scheduler down. Radical. ### Scheduler#down? Returns true if the scheduler has been shut down. ### Scheduler#started_at Returns the Time instance at which the scheduler got started. ### Scheduler #uptime / #uptime_s Returns since the count of seconds for which the scheduler has been running. ```#uptime_s``` returns this count in a String easier to grasp for humans, like ```"3d12m45s123"```. ### Scheduler#join Lets the current thread join the scheduling thread in rufus-scheduler. The thread comes back when the scheduler gets shut down. `#join` is mostly used in standalone scheduling script (or tiny one file examples). Calling `#join` from a web application initializer will probably hijack the main thread and prevent the web application from being served. Do not put a `#join` in such a web application initializer file. ### Scheduler#threads Returns all the threads associated with the scheduler, including the scheduler thread itself. ### Scheduler#work_threads(query=:all/:active/:vacant) Lists the work threads associated with the scheduler. The query option defaults to :all. * :all : all the work threads * :active : all the work threads currently running a Job * :vacant : all the work threads currently not running a Job Note that the main schedule thread will be returned if it is currently running a Job (ie one of those `blocking: true` jobs). ### Scheduler#scheduled?(job_or_job_id) Returns true if the arg is a currently scheduled job (see Job#scheduled?). ### Scheduler#occurrences(time0, time1) Returns a hash `{ job => [ t0, t1, ... ] }` mapping jobs to their potential trigger time within the `[ time0, time1 ]` span. Please note that, for interval jobs, the ```#mean_work_time``` is used, so the result is only a prediction. ### Scheduler#timeline(time0, time1) Like `#occurrences` but returns a list ```[ [ t0, job0 ], [ t1, job1 ], ... ]``` of time + job pairs. ## dealing with job errors The easy, job-granular way of dealing with errors is to rescue and deal with them immediately. The two next sections show examples. Skip them for explanations on how to deal with errors at the scheduler level. ### block jobs As said, jobs could take care of their errors themselves. ```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 abundant details to $stderr. If, for example, you'd like to divert that flow to another file (descriptor), you can reassign $stderr for the current Ruby process ```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 ``` On Rails, the `on_error` method redefinition might look like: ```ruby def scheduler.on_error(job, error) Rails.logger.error( "err#{error.object_id} rufus-scheduler intercepted #{error.inspect}" + " in job #{job.inspect}") error.backtrace.each_with_index do |line, i| Rails.logger.error( "err#{error.object_id} #{i}: #{line}") end end ``` ## Callbacks ### Rufus::Scheduler #on_pre_trigger and #on_post_trigger callbacks One can bind callbacks before and after jobs trigger: ```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 where the job execution really happens). ### Rufus::Scheduler#around_trigger One can create an around callback which will wrap a job: ```ruby def s.around_trigger(job) t = Time.now puts "Starting job #{job.id}..." yield puts "job #{job.id} finished in #{Time.now-t} seconds." end ``` The around callback is executed in the thread. ### Rufus::Scheduler#on_pre_trigger as a guard Returning ```false``` in on_pre_trigger will prevent the job from triggering. Returning anything else (nil, -1, true, ...) will let the job trigger. Note: your business logic should go in the scheduled block itself (or the scheduled instance). Don't put business logic in on_pre_trigger. Return false for admin reasons (backend down, etc), not for business reasons that are tied to the job itself. ```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 schedulers sharing the same lockfile) is running. This is useful in environments where the Ruby process holding the scheduler gets started multiple times. If the lockfile mechanism here is not sufficient, you can plug your custom mechanism. It's explained in [advanced lock schemes](#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 singleton 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 mechanism prevents schedulers that have not set/created the lockfile from running. There are situations where this is not sufficient. By overriding #lock and #unlock, one can customize how schedulers lock. This example was provided by [Eric Lindvall](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](https://zookeeper.apache.org/) to make sure only one scheduler in a group of distributed schedulers runs. The methods #lock and #unlock are overridden and #confirm_lock is provided, to make sure that the lock is still valid. The #confirm_lock method is called right before a job triggers (if it is provided). The more generic callback #on_pre_trigger is called right after #confirm_lock. ### :scheduler_lock and :trigger_lock (introduced in rufus-scheduler 3.0.9). Another way of prodiving `#lock`, `#unlock` and `#confirm_lock` to a rufus-scheduler is by using the `:scheduler_lock` and `:trigger_lock` options. See [:trigger_lock](#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 (Please note that [fugit](https://github.com/floraison/fugit) does the heavy-lifting parsing work for rufus-scheduler). Rufus::Scheduler provides a class method ```.parse``` to parse time durations and cron strings. It's what it's using when receiving schedules. One can use it directly (no need to instantiate a Scheduler). ```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 input is a duration and a Fugit::Cron instance when the input is a cron string. It will raise an ArgumentError if it can't parse the input. Beyond ```.parse```, there are also ```.parse_cron``` and ```.parse_duration```, for finer granularity. There is an interesting helper method named ```.to_duration_hash```: ```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.to_s # => 2013-11-04 00:00:00 +0900 ``` #### L (last day of month) L can be used in the "day" slot: In this example, the cronline is supposed to trigger every last day of the month at noon: ```ruby require 'rufus-scheduler' Time.now # => 2013-10-26 07:22:09 +0900 Rufus::Scheduler.parse('00 12 L * *').next_time.to_s # => 2013-10-31 12:00:00 +0900 ``` #### negative day (x days before the end of the month) It's OK to pass negative values in the "day" slot: ```ruby scheduler.cron '0 0 -5 * *' do # do it at 00h00 5 days before the end of the month... end ``` Negative ranges (`-10--5-`: 10 days before the end of the month to 5 days before the end of the month) are OK, but mixed positive / negative ranges will raise an `ArgumentError`. Negative ranges with increments (`-10---2/2`) are accepted as well. Descending day ranges are not accepted (`10-8` or `-8--10` for example). ## a note about timezones Cron schedules and at schedules support the specification of a timezone. ```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") # => #, @time=nil> ``` ### I get "zotime.rb:41:in `initialize': cannot determine timezone from nil" For when you see an error like: ``` rufus-scheduler/lib/rufus/scheduler/zotime.rb:41: in `initialize': cannot determine timezone from nil (etz:nil,tnz:"中国标准时间",tzid:nil) (ArgumentError) from rufus-scheduler/lib/rufus/scheduler/zotime.rb:198:in `new' from rufus-scheduler/lib/rufus/scheduler/zotime.rb:198:in `now' from rufus-scheduler/lib/rufus/scheduler.rb:561:in `start' ... ``` It may happen on Windows or on systems that poorly hint to Ruby which timezone to use. It should be solved by setting explicitly the `ENV['TZ']` before the scheduler instantiation: ```ruby ENV['TZ'] = 'Asia/Shanghai' scheduler = Rufus::Scheduler.new scheduler.every '2s' do puts "#{Time.now} Hello #{ENV['TZ']}!" end ``` On Rails you might want to try with: ```ruby ENV['TZ'] = Time.zone.name # Rails only scheduler = Rufus::Scheduler.new scheduler.every '2s' do puts "#{Time.now} Hello #{ENV['TZ']}!" end ``` (Hat tip to Alexander in [gh-230](https://github.com/jmettraux/rufus-scheduler/issues/230)) Rails sets its timezone under `config/application.rb`. Rufus-Scheduler 3.3.3 detects the presence of Rails and uses its timezone setting (tested with Rails 4), so setting `ENV['TZ']` should not be necessary. The value can be determined thanks to [https://en.wikipedia.org/wiki/List_of_tz_database_time_zones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Use a "continent/city" identifier (for example "Asia/Shanghai"). Do not use an abbreviation (not "CST") and do not use a local time zone name (not "中国标准时间" nor "Eastern Standard Time" which, for instance, points to a time zone in America and to another one in Australia...). If the error persists (and especially on Windows), try to add the `tzinfo-data` to your Gemfile, as in: ```ruby gem 'tzinfo-data' ``` or by manually requiring it before requiring rufus-scheduler (if you don't use Bundler): ```ruby require 'tzinfo/data' require 'rufus-scheduler' ``` ## 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. ### avoid scheduling when running the Ruby on Rails console (Written in reply to [gh-186](https://github.com/jmettraux/rufus-scheduler/issues/186)) If you don't want rufus-scheduler to trigger anything while running the Ruby on Rails console, running for tests/specs, or running from a Rake task, you can insert a conditional return statement before jobs are added to the scheduler instance: ```ruby # # config/initializers/scheduler.rb require 'rufus-scheduler' s = Rufus::Scheduler.singleton return if defined?(Rails::Console) || Rails.env.test? || File.split($0).last == 'rake' # return if $PROGRAM_NAME.include?('spring') # see https://github.com/jmettraux/rufus-scheduler/issues/186 # do not schedule when Rails is run from its console, for a test/spec, or # from a Rake task s.every '1m' do Rails.logger.info "hello, it's #{Time.now}" Rails.logger.flush end ``` ### 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: * https://www.mikeperham.com/2014/09/22/dont-daemonize-your-daemons/ * https://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.8.0/TODO.txt000066400000000000000000000137121407342460500161610ustar00rootroot00000000000000 [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.8.0/lib/000077500000000000000000000000001407342460500154155ustar00rootroot00000000000000rufus-scheduler-3.8.0/lib/rufus-scheduler.rb000066400000000000000000000000341407342460500210570ustar00rootroot00000000000000 require 'rufus/scheduler' rufus-scheduler-3.8.0/lib/rufus/000077500000000000000000000000001407342460500165615ustar00rootroot00000000000000rufus-scheduler-3.8.0/lib/rufus/scheduler.rb000066400000000000000000000414211407342460500210660ustar00rootroot00000000000000 require 'date' if RUBY_VERSION < '1.9.0' require 'thread' require 'fugit' module Rufus; end class Rufus::Scheduler VERSION = '3.8.0' EoTime = ::EtOrbi::EoTime require 'rufus/scheduler/util' require 'rufus/scheduler/jobs_core' require 'rufus/scheduler/jobs_one_time' require 'rufus/scheduler/jobs_repeat' require 'rufus/scheduler/job_array' require 'rufus/scheduler/locks' # # 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_accessor :discard_past attr_reader :started_at attr_reader :paused_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_at = nil @jobs = JobArray.new @frequency = Rufus::Scheduler.parse(opts[:frequency] || 0.300) @discard_past = opts.has_key?(:discard_past) ? opts[:discard_past] : true @mutexes = {} @work_queue = Queue.new @join_queue = Queue.new #@min_work_threads = # opts[:min_work_threads] || opts[:min_worker_threads] || # MIN_WORK_THREADS @max_work_threads = opts[:max_work_threads] || opts[:max_worker_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. 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.x, use .new instead of .start_new' end def uptime @started_at ? EoTime.now - @started_at : nil end def around_trigger(job) yield end def uptime_s uptime ? self.class.to_duration(uptime) : '' end def join(time_limit=nil) fail NotRunningError.new('cannot join scheduler that is not running') \ unless @thread fail ThreadError.new('scheduler thread cannot join itself') \ if @thread == Thread.current if time_limit time_limit_join(time_limit) else no_time_limit_join end end def down? ! @started_at end def up? !! @started_at end def paused? !! @paused_at end def pause @paused_at = EoTime.now end def resume(opts={}) dp = opts[:discard_past] jobs.each { |job| job.resume_discard_past = dp } @paused_at = nil 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) callable, opts = nil, callable if callable.is_a?(Hash) opts = opts.dup opts[:_t] = Rufus::Scheduler.parse(arg, opts) case opts[:_t] when ::Fugit::Cron then schedule_cron(arg, callable, opts, &block) when ::EtOrbi::EoTime, Time then schedule_at(arg, callable, opts, &block) else schedule_in(arg, callable, opts, &block) end end def repeat(arg, callable=nil, opts={}, &block) callable, opts = nil, callable if callable.is_a?(Hash) opts = opts.dup opts[:_t] = Rufus::Scheduler.parse(arg, opts) case opts[:_t] when ::Fugit::Cron 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(&: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, _ = 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 currently 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_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, _)| 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}") stderr.puts(" #{pre} #{job.source_location.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} local_tzone: #{EoTime.local_tzone.inspect}") stderr.puts(" #{pre} et-orbi:") stderr.puts(" #{pre} #{EoTime.platform_info}") 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} frequency: #{frequency.inspect}") stderr.puts(" #{pre} discard_past: #{discard_past.inspect}") stderr.puts(" #{pre} started_at: #{started_at.inspect}") stderr.puts(" #{pre} paused_at: #{paused_at.inspect}") 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:") stderr.puts(" #{pre} size: #{@work_queue.size}") stderr.puts(" #{pre} num_waiting: #{@work_queue.num_waiting}") stderr.puts(" #{pre} join_queue:") stderr.puts(" #{pre} size: #{@join_queue.size}") stderr.puts(" #{pre} num_waiting: #{@join_queue.num_waiting}") stderr.puts("} #{pre} .") rescue => e stderr.puts("failure in #on_error itself:") stderr.puts(e.inspect) stderr.puts(e.backtrace) ensure stderr.flush end def shutdown(opt=nil) opts = case opt when Symbol then { opt => true } when Hash then opt else {} end @jobs.unschedule_all if opts[:wait] || opts[:join] join_shutdown(opts) elsif opts[:kill] kill_shutdown(opts) else regular_shutdown(opts) end @work_queue.clear unlock @thread.join end alias stop shutdown protected def join_shutdown(opts) limit = opts[:wait] || opts[:join] limit = limit.is_a?(Numeric) ? limit : nil #@started_at = nil # # when @started_at is nil, the scheduler thread exits, here # we want it to exit when all the work threads have been joined # hence it's set to nil later on # @paused_at = EoTime.now (work_threads.size * 2 + 1).times { @work_queue << :shutdown } work_threads .collect { |wt| wt == Thread.current ? nil : Thread.new { wt.join(limit); wt.kill } } .each { |st| st.join if st } @started_at = nil end def kill_shutdown(opts) @started_at = nil work_threads.each(&:kill) end def regular_shutdown(opts) @started_at = nil end def time_limit_join(limit) fail ArgumentError.new("limit #{limit.inspect} should be > 0") \ unless limit.is_a?(Numeric) && limit > 0 t0 = monow f = [ limit.to_f / 20, 0.100 ].min while monow - t0 < limit r = begin @join_queue.pop(true) rescue ThreadError => e # # false end return r if r sleep(f) end nil end def no_time_limit_join @join_queue.pop end # 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 free_all_work_threads # # work_threads.each { |t| t.raise(KillSignal) } #end def start @started_at = EoTime.now @thread = Thread.new do while @started_at do unschedule_jobs trigger_jobs unless @paused_at timeout_jobs sleep(@frequency) end rejoin 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 = EoTime.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 = ts + to unless to.is_a?(EoTime) next if to > EoTime.now t.raise(Rufus::Scheduler::TimeoutError) end end def rejoin (@join_queue.num_waiting * 2 + 1).times { @join_queue << @thread } 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) opts = opts.dup unless opts.has_key?(:_t) return_job_instance ||= opts[:job] job_class = case job_type when :once opts[:_t] ||= Rufus::Scheduler.parse(t, opts) opts[:_t].is_a?(Numeric) ? InJob : AtJob when :every EveryJob when :interval IntervalJob when :cron CronJob end job = job_class.new(self, t, opts, block || callable) job.check_frequency @jobs.push(job) return_job_instance ? job : job.job_id end def monow; self.class.monow; end def ltstamp; self.class.ltstamp; end end rufus-scheduler-3.8.0/lib/rufus/scheduler/000077500000000000000000000000001407342460500205375ustar00rootroot00000000000000rufus-scheduler-3.8.0/lib/rufus/scheduler/job_array.rb000066400000000000000000000015441407342460500230400ustar00rootroot00000000000000 # # The array rufus-scheduler uses to keep jobs in order (next to trigger # first). # class Rufus::Scheduler::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 do |job| job.next_time || (now + 1) end.each do |job| nt = job.next_time break if ( ! nt) || (nt > 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 def unschedule_all @array.each(&:unschedule) end end rufus-scheduler-3.8.0/lib/rufus/scheduler/jobs_core.rb000066400000000000000000000161011407342460500230300ustar00rootroot00000000000000 class Rufus::Scheduler::Job EoTime = ::EtOrbi::EoTime # # 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 :locals attr_reader :count attr_reader :last_work_time attr_reader :mean_work_time attr_accessor :name # next trigger time # attr_accessor :next_time # previous "next trigger time" # attr_accessor :previous_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 # Default, core, implementation has no effect. Repeat jobs do override it. # def resume_discard_past=(v); end 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 = EoTime.now @unscheduled_at = nil @last_time = nil @locals = opts[:locals] || opts[:l] || {} @local_mutex = Mutex.new @id = determine_id @name = opts[:name] || opts[:n] 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 source_location @callable.source_location end alias location source_location # Will fail with an ArgumentError if the job frequency is higher than # the scheduler frequency. # def check_frequency # this parent implementation never fails end def trigger(time) @previous_time = @next_time set_next_time(time) do_trigger(time) end # Trigger the job right now, off of its schedule. # # Done in collaboration with Piavka in # https://github.com/jmettraux/rufus-scheduler/issues/214 # def trigger_off_schedule(time=EoTime.now) do_trigger(time) end def unschedule @unscheduled_at = EoTime.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 has_key?(key) @local_mutex.synchronize { @locals.has_key?(key) } end alias key? has_key? def keys; @local_mutex.synchronize { @locals.keys }; end def values; @local_mutex.synchronize { @locals.values }; end def entries; @local_mutex.synchronize { @locals.entries }; 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 def next_times(count) next_time ? [ next_time ] : [] end # 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(EoTime.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] @scheduler.around_trigger(self) do @callable.call(*args) end 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) return if ( opts[:overlap] == false && running? ) return if ( callback(:confirm_lock, time) && callback(:on_pre_trigger, time) ) == false @count += 1 if opts[:blocking] trigger_now(time) else trigger_queue(time) end end def trigger_now(time) ct = Thread.current t = EoTime.now # if there are mutexes, t might be really bigger than time ct[:rufus_scheduler_job] = self ct[:rufus_scheduler_time] = t ct[:rufus_scheduler_timeout] = compute_timeout @last_time = t do_call(time, true) ensure @last_work_time = EoTime.now - ct[:rufus_scheduler_time] @mean_work_time = ((@count - 1) * @mean_work_time + @last_work_time) / @count post_trigger(time) ct[:rufus_scheduler_job] = nil ct[:rufus_scheduler_time] = nil ct[:rufus_scheduler_timeout] = nil end def post_trigger(time) set_next_time(time, true) # except IntervalJob instances, jobs will ignore this call callback(:on_post_trigger, time) end def start_work_thread thread = Thread.new do ct = Thread.current ct[:rufus_scheduler_job] = true # indicates that the thread is going to be assigned immediately ct[@scheduler.thread_key] = true ct[:rufus_scheduler_work_thread] = true loop do break if @scheduler.started_at == nil job, time = @scheduler.work_queue.pop break if job == :shutdown break if @scheduler.started_at == nil next if job.unscheduled_at begin (job.opts[:mutex] || []).reduce( lambda { job.trigger_now(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 thread end def trigger_queue(time) threads = @scheduler.work_threads vac = threads.select { |t| t[:rufus_scheduler_job] == nil }.size que = @scheduler.work_queue.size cur = threads.size max = @scheduler.max_work_threads start_work_thread if vac - que < 1 && cur < max @scheduler.work_queue << [ self, time ] end end rufus-scheduler-3.8.0/lib/rufus/scheduler/jobs_one_time.rb000066400000000000000000000021111407342460500236730ustar00rootroot00000000000000 class Rufus::Scheduler::OneTimeJob < Rufus::Scheduler::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.object_id < 0 ? 'm' : '') + self.object_id.to_s ].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, now=nil) @next_time = is_post ? nil : false end end class Rufus::Scheduler::AtJob < Rufus::Scheduler::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 Rufus::Scheduler::InJob < Rufus::Scheduler::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 rufus-scheduler-3.8.0/lib/rufus/scheduler/jobs_repeat.rb000066400000000000000000000150121407342460500233600ustar00rootroot00000000000000 class Rufus::Scheduler::RepeatJob < Rufus::Scheduler::Job attr_reader :paused_at attr_reader :first_at attr_reader :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?(Integer) 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 FIRSTS = [ :now, :immediately, 0 ].freeze def first_at=(first) return (@first_at = nil) if first == nil n0 = EoTime.now n1 = n0 + 0.003 first = n0 if FIRSTS.include?(first) fdur = Rufus::Scheduler.parse_duration(first, no_error: true) @first_at = (fdur && (EoTime.now + fdur)) || EoTime.make(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 = if last ldur = Rufus::Scheduler.parse_duration(last, no_error: true) (ldur && (EoTime.now + ldur)) || EoTime.make(last) else nil end fail ArgumentError.new( "cannot set last[_at|_in] in the past: " + "#{last.inspect} -> #{@last_at.inspect}" ) if last && @last_at < EoTime.now @last_at end def trigger(time) return if @paused_at #return set_next_time(time) if @paused_at return (@next_time = nil) if @times && @times < 1 return (@next_time = nil) if @last_at && time >= @last_at # # It keeps jobs one step too much in @jobs, but it's OK super @times -= 1 if @times end def pause @paused_at = EoTime.now end def resume(opts={}) @resume_discard_past = opts[:discard_past] #p [ :@resume_discard_past, @resume_discard_past ] @paused_at = nil end def paused? !! @paused_at end def determine_id [ self.class.name.split(':').last.downcase[0..-4], @scheduled_at.to_f, (self.object_id < 0 ? 'm' : '') + self.object_id.to_s ].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 # Starting from now, returns the {count} next occurences # (EtOrbi::EoTime instances) for this job. # # Warning, for IntervalJob, the @mean_work_time is used since # "interval" works from the end of a job to its next trigger # (not from one trigger to the next, as for "cron" and "every"). # def next_times(count) (count - 1).times.inject([ next_time ]) { |a| a << next_time_from(a.last) a } end protected def discard_past? dp = @scheduler.discard_past dp = @discard_past if @discard_past != nil dp = @resume_discard_past if @resume_discard_past != nil dp end end # # A parent class of EveryJob and IntervalJob # class Rufus::Scheduler::EvInJob < Rufus::Scheduler::RepeatJob def first_at=(first) @next_time = super end end class Rufus::Scheduler::EveryJob < Rufus::Scheduler::EvInJob attr_reader :frequency attr_accessor :resume_discard_past def initialize(scheduler, duration, opts, block) super(scheduler, duration, opts, block) @frequency = Rufus::Scheduler.parse_in(@original) @discard_past = opts[:discard_past] fail ArgumentError.new( "cannot schedule #{self.class} with a frequency " + "of #{@frequency.inspect} (#{@original.inspect})" ) if @frequency <= 0 set_next_time(nil) end def check_frequency fail ArgumentError.new( "job frequency (#{@frequency}s) is higher than " + "scheduler frequency (#{@scheduler.frequency}s)" ) if @frequency < @scheduler.frequency end def next_time_from(time) time + @frequency end protected def set_next_time(trigger_time, is_post=false, now=nil) return if is_post n = now || EoTime.now return @next_time = @first_at \ if @first_at && (trigger_time == nil || @first_at > n) dp = discard_past? loop do @next_time = (@next_time || n) + @frequency break if dp == false break if @next_time > n end end end class Rufus::Scheduler::IntervalJob < Rufus::Scheduler::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 def next_time_from(time) time + @mean_work_time + @interval end protected def set_next_time(trigger_time, is_post=false, now=nil) n = now || EoTime.now @next_time = if is_post n + @interval elsif trigger_time.nil? if @first_at == nil || @first_at < n n + @interval else @first_at end else false end end end class Rufus::Scheduler::CronJob < Rufus::Scheduler::RepeatJob attr_reader :cron_line def initialize(scheduler, cronline, opts, block) super(scheduler, cronline, opts, block) @cron_line = opts[:_t] || ::Fugit::Cron.do_parse(cronline) set_next_time(nil) end def check_frequency return if @scheduler.frequency <= 1 # # The minimum time delta in a cron job is 1 second, so if the # scheduler frequency is less than that, no worries. f = @cron_line.rough_frequency fail ArgumentError.new( "job frequency (min ~#{f}s) is higher than " + "scheduler frequency (#{@scheduler.frequency}s)" ) if f < @scheduler.frequency end def brute_frequency @cron_line.brute_frequency end def rough_frequency @cron_line.rough_frequency end def next_time_from(time) @cron_line.next_time(time) end protected def set_next_time(trigger_time, is_post=false, now=nil) return if is_post t = trigger_time || now || EoTime.now previous = @previous_time || @scheduled_at t = previous if ! discard_past? && t > previous @next_time = if @first_at && @first_at > t @first_at else @cron_line.next_time(t) end end end rufus-scheduler-3.8.0/lib/rufus/scheduler/locks.rb000066400000000000000000000022041407342460500221750ustar00rootroot00000000000000 require 'fileutils' # # A lock that can always be acquired # class Rufus::Scheduler::NullLock # Locking is always successful. # def lock; true; end def locked?; true; end def unlock; true; end end # # The standard flock mechanism, with its own class thanks to @ecin # class Rufus::Scheduler::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 rufus-scheduler-3.8.0/lib/rufus/scheduler/util.rb000066400000000000000000000133471407342460500220510ustar00rootroot00000000000000 class Rufus::Scheduler class << self #-- # time and string methods #++ def 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.inspect} (#{o.class})")) end def parse_cron(o, opts={}) opts[:no_error] ? Fugit.parse_cron(o) : Fugit.do_parse_cron(o) end def parse_in(o, opts={}) #o.is_a?(String) ? parse_duration(o, opts) : o return parse_duration(o, opts) if o.is_a?(String) return o if o.is_a?(Numeric) fail ArgumentError.new("couldn't parse time point in #{o.inspect}") rescue ArgumentError => ae return nil if opts[:no_error] fail ae end def parse_at(o, opts={}) return o if o.is_a?(EoTime) return EoTime.make(o) if o.is_a?(Time) EoTime.parse(o, opts) rescue StandardError => se return nil if opts[:no_error] fail se end # 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 parse_duration(str, opts={}) d = opts[:no_error] ? Fugit::Duration.parse(str, opts) : Fugit::Duration.do_parse(str, opts) d ? d.to_sec : nil 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 to_duration(seconds, options={}) #d = Fugit::Duration.parse(seconds, options).deflate #d = d.drop_seconds if options[:drop_seconds] #d = d.deflate(:month => options[:months]) if options[:months] #d.to_rufus_s to_fugit_duration(seconds, options).to_rufus_s end # Turns a number of seconds (integer or Float) into a hash like in : # # Rufus.to_duration_hash 0.051 # # => { :s => 0.051 } # Rufus.to_duration_hash 7.051 # # => { :s => 7.051 } # Rufus.to_duration_hash 0.120 + 30 * 24 * 3600 + 1 # # => { :w => 4, :d => 2, :s => 1.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 to_duration_hash(seconds, options={}) to_fugit_duration(seconds, options).to_rufus_h end # Used by both .to_duration and .to_duration_hash # def to_fugit_duration(seconds, options={}) d = Fugit::Duration .parse(seconds, options) .deflate d = d.drop_seconds if options[:drop_seconds] d = d.deflate(:month => options[:months]) if options[:months] d end #-- # misc #++ if RUBY_VERSION > '1.9.9' # Produces the UTC string representation of a Time instance # # like "2009/11/23 11:11:50.947109 UTC" # def utc_to_s(t=Time.now) "#{t.dup.utc.strftime('%F %T.%6N')} UTC" end # Produces a hour/min/sec/milli string representation of Time instance # def h_to_s(t=Time.now) t.strftime('%T.%6N') end else def utc_to_s(t=Time.now) "#{t.utc.strftime('%Y-%m-%d %H:%M:%S')}.#{sprintf('%06d', t.usec)} UTC" end def h_to_s(t=Time.now) "#{t.strftime('%H:%M:%S')}.#{sprintf('%06d', t.usec)}" end end if defined?(Process::CLOCK_MONOTONIC) def monow; Process.clock_gettime(Process::CLOCK_MONOTONIC); end else def monow; Time.now.to_f; end end def ltstamp; Time.now.strftime('%FT%T.%3N'); end end # Debugging tools... # class D def self.h_to_s(t=Time.now); Rufus::Scheduler.h_to_s(t); end end end rufus-scheduler-3.8.0/misc/000077500000000000000000000000001407342460500156025ustar00rootroot00000000000000rufus-scheduler-3.8.0/misc/cronline_next_time_cost.rb000066400000000000000000000004111407342460500230400ustar00rootroot00000000000000 $:.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.8.0/misc/freq.rb000066400000000000000000000006061407342460500170660ustar00rootroot00000000000000 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.8.0/misc/gacha_test.rb000066400000000000000000000033141407342460500202320ustar00rootroot00000000000000 # # 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.8.0/misc/kssminus_38k_jobs.rb000066400000000000000000000006351407342460500215110ustar00rootroot00000000000000 require 'rufus-scheduler' p [ RUBY_VERSION, RUBY_PLATFORM ] crons = [ '* * * * *', '*/5 * * * *', '*/10 * * * *', '10 4 * * *', '35 */3 * * *', '* */3 * * *', '16 */4 * * *', '30 14 * * *', '26 */2 * * *' ] total = 38_000 / crons.length crons.each do |cron| s = Rufus::Scheduler.new t0 = Time.now total.times do s.cron(cron) {} end p [ cron, Time.now - t0 ] s.shutdown end rufus-scheduler-3.8.0/misc/kssminus_38k_jobs_rprof.rb000066400000000000000000000010461407342460500227160ustar00rootroot00000000000000 require 'ruby-prof' require 'rufus-scheduler' p [ RUBY_VERSION, RUBY_PLATFORM ] s = Rufus::Scheduler.new t = Time.now profile = RubyProf.profile do 10.times do s.cron('*/5 * * * *') {} end end p Time.now - t #printer = RubyProf::GraphPrinter.new(profile) #printer = RubyProf::GraphHtmlPrinter.new(profile) #printer = RubyProf::CallTreePrinter.new(profile) #printer = RubyProf::DotPrinter.new(profile) #printer.print(STDOUT, {}) printer = RubyProf::CallStackPrinter.new(profile) File.open('out.html', 'wb') { |f| printer.print(f, {}) } rufus-scheduler-3.8.0/misc/six_field_cronline_test.rb000077500000000000000000000033141407342460500230310ustar00rootroot00000000000000#!/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.8.0/misc/tz_all.rb000066400000000000000000000005751407342460500174230ustar00rootroot00000000000000 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.8.0/misc/tz_all.txt000066400000000000000000000220451407342460500176330ustar00rootroot00000000000000 # # 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.8.0/rufus-scheduler.gemspec000066400000000000000000000026271407342460500213430ustar00rootroot00000000000000 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 = 'https://github.com/jmettraux/rufus-scheduler' 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). Not a replacement for crond. }.strip s.metadata = { 'changelog_uri' => s.homepage + '/blob/master/CHANGELOG.md', 'bug_tracker_uri' => s.homepage + '/issues', 'homepage_uri' => s.homepage, 'source_code_uri' => s.homepage, #'wiki_uri' => s.homepage + '/flor/wiki', #'documentation_uri' => s.homepage + '/tree/master/doc', #'mailing_list_uri' => 'https://groups.google.com/forum/#!forum/floraison', } #s.files = `git ls-files`.split("\n") s.files = Dir[ 'README.{md,txt}', 'CHANGELOG.{md,txt}', 'CREDITS.{md,txt}', 'LICENSE.{md,txt}', 'Makefile', 'lib/**/*.rb', #'spec/**/*.rb', 'test/**/*.rb', "#{s.name}.gemspec", ] s.required_ruby_version = '>= 1.9' s.add_runtime_dependency 'fugit', '~> 1.1', '>= 1.1.6' s.add_development_dependency 'rspec', '~> 3.7' s.add_development_dependency 'chronic', '~> 0.10' s.require_path = 'lib' end rufus-scheduler-3.8.0/spec/000077500000000000000000000000001407342460500156015ustar00rootroot00000000000000rufus-scheduler-3.8.0/spec/basics_spec.rb000066400000000000000000000023011407342460500204000ustar00rootroot00000000000000 # # 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' : '') [ time.strftime('%Y-%m-%d %H:%M:%S'), time.utc_offset.to_s, time.dst? ? 'dst' : '' ].select { |s| s.length > 0 }.join(' ') 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 3600') expect( tts(Time.new(2014, 8, 1, 1, 0, 0, '+01:00')) ).to eq('2014-08-01 01:00:00 3600') expect( tts(Time.new(2014, 8, 1, 1, 0, 0, '+01:00')) ).to eq('2014-08-01 01:00:00 3600') 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 3600') expect( tts(in_zone('Europe/Berlin') { Time.local(2014, 8, 1, 1, 0, 0) }) ).to eq('2014-08-01 01:00:00 7200 dst') end end end rufus-scheduler-3.8.0/spec/error_spec.rb000066400000000000000000000047301407342460500202750ustar00rootroot00000000000000 # # 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.8.0/spec/job_array_spec.rb000066400000000000000000000011571407342460500211140ustar00rootroot00000000000000 # # 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.8.0/spec/job_at_spec.rb000066400000000000000000000032401407342460500203750ustar00rootroot00000000000000 # # 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_f).to eq(t.to_f) end end describe '#previous_time' do it 'returns the previous #time' do t = Time.now + 1 t0 = nil t1 = nil job = @scheduler.schedule_at t do |j| t1 = Time.now t0 = j.previous_time end sleep 1.4 expect(t0.to_f).to eq(t.to_f) expect(t1).to be > t end end describe '#next_times' do it 'returns the next n times' do job = @scheduler.schedule_at Time.now + 1 do; end expect(job.next_times(3)).to eq([ job.next_time ]) end it 'returns an empty array if it already triggered' do job = @scheduler.schedule_at Time.now + 0.001 do; end sleep 0.350 expect(job.next_times(3)).to eq([]) end end end rufus-scheduler-3.8.0/spec/job_cron_spec.rb000066400000000000000000000132051407342460500207340ustar00rootroot00000000000000 # # 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 context 'overlap, gh-304' do it 'does not trash start times (cron min)' do starts = [] ends = [] @scheduler.cron '* * * * *' do |job| c = job.count starts << Time.now sleep 65 ends << c end wait_until(5 * 60) { starts.count > 2 } #p starts secs = starts.collect(&:sec) expect(secs).to eq([ 0, 0, 0 ]) ss = starts.collect { |s| Time.local(s.year, s.month, s.day, s.hour, s.min, 0) } expect((ss[1] - ss[0]).to_i).to eq(60) expect((ss[2] - ss[1]).to_i).to eq(60) end it 'does not trash start times (cron sec)' do starts = [] ends = [] @scheduler.cron '* * * * * *' do |job| c = job.count starts << Time.now sleep 1.5 ends << c end ss = wait_until(5 * 60) { starts.count > 5 && starts.dup } secs = ss.collect(&:sec) expect(secs.uniq.length).to eq(secs.length) ts = ss .map { |s| Time.local(s.year, s.month, s.day, s.hour, s.min, s.sec) } ds = ts .each_with_index .collect { |s, i| i == 0 ? 1 : (s - ts[i - 1]).to_i } expect(ds.uniq).to eq([ 1 ]) end end describe '#next_time' do it 'returns the next trigger time' do tomorrow = Time.now + 24 * 3600 # tomorrow nt = @scheduler.schedule_cron("0 0 #{tomorrow.day} * *", lambda {}).next_time expect(nt.to_f).to eq(Time.parse(tomorrow.strftime('%Y-%m-%d')).to_f) expect(nt.zone._name).to eq(EtOrbi::EoTime.local_tzone._name) 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) {} nt = job.next_time expect(nt.to_f).to eq(ft.to_f) expect(nt.zone._name).to eq(EtOrbi::EoTime.local_tzone._name) end end describe '#next_times' do it 'returns the next n times' do job = @scheduler.schedule_cron '1 * * * *' do; end times = 2.times.inject([ job.next_time ]) { |a| a << job.next_time_from(a.last) a } expect(job.next_times(3)).to eq(times) end it 'takes first_at/in into account' do job = @scheduler.schedule_cron '* * * * * *', first_in: '3s' do; end times = 2.times.inject([ job.next_time ]) { |a| a << job.next_time_from(a.last) a } expect(job.next_times(3)).to eq(times) expect(times.first).to be_between(Time.now + 2.5, Time.now + 3.5) end end describe '#resume' do context 'discard_past: true' do # Discard_past can be set at scheduler level, at job level, and # at resume level. # Test only the last case here. # Every tests them all. it 'discards' do @scheduler.discard_past = false job = @scheduler .schedule_cron('* * * * * *', discard_past: false) do; end job.pause expect(job.count).to eq(0) wait_next_seconds(2) job.resume(discard_past: true) wait_until { job.count > 0 } expect(job.count).to eq(1) end end context 'discard_past: false' do # Discard_past can be set at scheduler level, at job level, and # at resume level. # Test only the last case here. # Every tests them all. it 'triggers the past' do job = @scheduler.schedule_cron('* * * * * *', discard_past: false) do; end job.pause expect(job.count).to eq(0) wait_next_seconds(3) expect(job.count).to eq(0) job.resume(discard_past: false) wait_next_second expect(job.count).to be > 2 end end end end rufus-scheduler-3.8.0/spec/job_every_spec.rb000066400000000000000000000151511407342460500211270ustar00rootroot00000000000000 # # 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 'strives to follow the given frequency (gh-181)' do # # duration = 60 * 60 # a = [ [ 0, Time.now ] ] # # @scheduler.every '60s' do |x| # n = Time.now # d = n - a.last[1] # a << [ d, n ] # print "#{d}" # print d >= 61 ? "...!!! " : " " # end # # sleep duration # end it 'lets its @next_time change in-flight' do times = [] @scheduler.every '1s' do |job| times << Time.now job.next_time = EtOrbi::EoTime.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 > 0.9 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_at => t + 1 do; end sleep 2 #p [ t, t.to_f ] #p [ job.last_time.to_s, job.last_time.to_f, job.last_time - t ] #p [ job.first_at.to_s, job.first_at.to_f, job.first_at - t ] #puts '.' #p [ job.next_time.to_s, job.next_time - t ] expect(job.first_at).to be_within_1s_of(t + 1.5) expect(job.last_time).to be_within_1s_of(job.first_at) expect(job.next_time).to be_within_1s_of(t + 4.5) end it 'triggers for the first time at first_in' 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.to_s, job.last_time.to_f, job.last_time - t ] #p [ job.first_at.to_s, job.first_at.to_f, job.first_at - t ] #puts '.' #p [ job.next_time.to_s, job.next_time - t ] expect(job.first_at).to be_within_1s_of(t + 1.5) expect(job.last_time).to be_within_1s_of(job.first_at) expect(job.next_time).to be_within_1s_of(t + 4.5) end it 'triggers once at first then repeatedly after the assigned time' do t = Time.now pt = nil job = @scheduler.schedule_every '4s', :first_in => '2s' do |j| n = Time.now if j.count == 1 expect(n).to be_within_1s_of(t + 2.3, '(count 1)') else expect(n).to be_within_1s_of(pt + 4.3, "(count #{job.count})") end pt = n end expect(job.first_at).to be_within_1s_of(t + 1.5) wait_until { job.count == 3 } expect(Time.now).to be_within_1s_of(t + 2 + 2 * 4) 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 describe '#previous_time' do it 'returns the previous #time' do t0 = nil t1 = nil job = @scheduler.schedule_every '1s' do |j| t1 = EtOrbi::EoTime.now t0 = j.previous_time end t = job.next_time sleep 1.4 expect(t0).to eq(t) expect(t1).to be > t end end end describe '#next_times' do it 'returns the next n times' do job = @scheduler.schedule_every '5m' do; end times = 2.times.inject([ job.next_time ]) { |a| a << job.next_time_from(a.last) a } expect(job.next_times(3)).to eq(times) end it 'takes first_at/in into account' do job = @scheduler.schedule_every '5m', first_in: 3 do; end times = 2.times.inject([ job.next_time ]) { |a| a << job.next_time_from(a.last) a } expect(job.next_times(3)).to eq(times) expect(times.first).to be_between(Time.now + 2.5, Time.now + 3.5) end end describe '#resume' do context 'discard_past: true' do it 'skips the skipped times' do #@scheduler.discard_past = true # this is the default job = @scheduler.schedule_every('1s') do; end job.pause expect(job.count).to eq(0) sleep 2 job.resume wait_until { job.count > 0 } expect(job.count).to eq(1) end it 'skips the skipped times' do @scheduler.discard_past = false job = @scheduler.schedule_every('1s', discard_past: true) do; end job.pause expect(job.count).to eq(0) sleep 2 job.resume wait_until { job.count > 0 } expect(job.count).to eq(1) end it 'skips the skipped times' do @scheduler.discard_past = false job = @scheduler.schedule_every('1s', discard_past: false) do; end job.pause expect(job.count).to eq(0) sleep 2 job.resume(discard_past: true) wait_until { job.count > 0 } expect(job.count).to eq(1) end end context 'discard_past: false' do it 'triggers the skipped times' do @scheduler.discard_past = false job = @scheduler.schedule_every('1s') do; end job.pause expect(job.count).to eq(0) sleep 2 job.resume sleep 1 expect(job.count).to be > 1 end it 'triggers the skipped times' do job = @scheduler.schedule_every('1s', discard_past: false) do; end job.pause expect(job.count).to eq(0) sleep 2 job.resume sleep 1 expect(job.count).to be > 1 end it 'triggers the skipped times' do job = @scheduler.schedule_every('1s') do; end job.pause expect(job.count).to eq(0) sleep 2 job.resume(discard_past: false) sleep 1 expect(job.count).to be > 1 end end end end rufus-scheduler-3.8.0/spec/job_in_spec.rb000066400000000000000000000011431407342460500203770ustar00rootroot00000000000000 # # 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 describe '#next_times' do it 'returns the next n times' do job = @scheduler.schedule_in '5m' do; end expect(job.next_times(3)).to eq([ job.next_time ]) end it 'returns an empty array if it already triggered' do job = @scheduler.schedule_in 0.001 do; end sleep 0.350 expect(job.next_times(3)).to eq([]) end end end rufus-scheduler-3.8.0/spec/job_interval_spec.rb000066400000000000000000000035511407342460500216220ustar00rootroot00000000000000 # # 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 describe '#next_times' do it 'returns the next n times' do job = @scheduler.schedule_interval '5m' do; end times = 2.times.inject([ job.next_time ]) { |a| a << job.next_time_from(a.last) a } expect(job.next_times(3)).to eq(times) end it 'takes first_at/in into account' do job = @scheduler.schedule_interval '5m', first_in: '3s' do; end times = 2.times.inject([ job.next_time ]) { |a| a << job.next_time_from(a.last) a } expect(job.next_times(3)).to eq(times) expect(times.first).to be_between(Time.now + 2.5, Time.now + 3.5) end end end rufus-scheduler-3.8.0/spec/job_repeat_spec.rb000066400000000000000000000212531407342460500212550ustar00rootroot00000000000000 # # 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 expect(job.paused_at).to eq(nil) job.pause expect(job.paused_at).not_to eq(nil) 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 expect(job.paused_at).to eq(nil) 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 expect(job.paused_at).to eq(nil) job.resume expect(job.paused?).to eq(false) expect(job.paused_at).to eq(nil) 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 #dump_zones t = Time.now + 10 job = @scheduler.schedule_every '0.5s', :first => t do; end expect( job.first_at.to_f ).to eq(t.to_f) expect( job.first_at.zone._name ).to eq(EtOrbi::EoTime.local_tzone._name) end it 'accepts a time string' do t = Time.now + 10 ts = t.to_s job = @scheduler.schedule_every '0.5s', :first => ts do; end expect(job.first_at.to_i).to eq(t.to_i) expect(job.first_at.utc_offset).to eq(t.utc_offset) 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 ||= EtOrbi::EoTime.now end sleep 0.7 expect(job.first_at.class).to eq(EtOrbi::EoTime) 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 ||= EtOrbi::EoTime.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 ||= EtOrbi::EoTime.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_f ).to eq(t.to_f) expect( job.last_at.zone._name ).to eq(EtOrbi::EoTime.local_tzone._name) 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 ts = t.to_s job = @scheduler.schedule_every '0.5s', :last => ts do; end expect(job.last_at.to_i).to eq(t.to_i) expect(job.last_at.utc_offset).to eq(t.utc_offset) 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 describe '#trigger_off_schedule' do it 'calls the job' do a = [] job = @scheduler.schedule_every('1s') { |j, t| a << t.to_f } job.trigger_off_schedule sleep 1.3 expect(a.length).to eq(2) expect(job.count).to eq(2) end it 'flags the job as running' do job = @scheduler.schedule_every('1y') { sleep 0.2 } expect(job.running?).to eq(false) job.trigger_off_schedule sleep 0.05 expect(job.running?).to eq(true) sleep 0.3 expect(job.running?).to eq(false) end end end rufus-scheduler-3.8.0/spec/job_spec.rb000066400000000000000000000416231407342460500177200ustar00rootroot00000000000000 # # 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 wait_until { job.last_time } 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 wait_until { job.threads.size > 0 } expect(job.threads.first[: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) } wait_until { job.running? } 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) } wait_until { job.running? } 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 wait_until { counter > 1 } 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 wait_until { job[:counter] && job[:counter] > 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?(:a)).to eq(false) expect(job.key?(:x)).to eq(true) end end describe '#has_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.has_key?(:a)).to eq(false) expect(job.has_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 describe '#values' do it 'returns the array of values of the job-local variables' do job = @scheduler.schedule_in '1s' do; end job[:x] = :y job['hello'] = :z job[123] = {} expect(job.values).to eq([ :y, :z, {} ]) end end describe '#entries' do it 'returns the array of entry pairs of the job-local variables' do job = @scheduler.schedule_in '1s' do; end job[:x] = :y job['hello'] = :z job[123] = {} expect(job.entries).to eq([ [ :x, :y ], [ 'hello', :z ], [ 123, {} ] ]) end end it 'can be set at job scheduling time' do j0 = @scheduler.schedule_in '1s', locals: { a: :alpha } do; end j1 = @scheduler.schedule_in '1s', l: { a: :aleph } do; end expect(j0[:a]).to eq(:alpha) expect(j1[:a]).to eq(:aleph) end it 'is accessible to pre, post, and around hooks before first run' do value = rand job = @scheduler.schedule_in('0.01s', l: { one: value }, times: 1) do $out << "in the job #{value}" end $out = [] def @scheduler.on_pre_trigger(job) $out << "pre #{job[:one]}" end def @scheduler.on_post_trigger(job) $out << "post #{job[:one]}" end def @scheduler.around_trigger(job) $out << "around-pre #{job[:one]}" yield $out << "around-post #{job[:one]}" end wait_until { $out.size > 4 } expect($out).to eq([ "pre #{value}", "around-pre #{value}", "in the job #{value}", "around-post #{value}", "post #{value}" ]) end describe '#name' do it 'returns the job name' do j = @scheduler.schedule_in '10d', name: 'alice' do; end expect(j.name).to eq('alice') end end describe '#location' do it 'returns the job location in code' do j = @scheduler.schedule_in '10d', name: 'alice' do; end l = j.location expect(l[0]).to match(/\/rufus-scheduler\/spec\/job_spec\.rb$/) expect(l[1]).to eq(__LINE__ - 5) end class InstanceHandler def call(job, time); end end it 'returns the right location for a callable instance job' do j = @scheduler.schedule_in '10d', InstanceHandler l = j.source_location expect(l[0]).to match(/\/rufus-scheduler\/spec\/job_spec\.rb$/) expect(l[1]).to eq(__LINE__ - 10) end it 'returns the right location for a callable class job' do j = @scheduler.schedule_in('10h', Class.new do def call; end end) l = j.source_location expect(l[0]).to match(/\/rufus-scheduler\/spec\/job_spec\.rb$/) expect(l[1]).to eq(__LINE__ - 6) end end describe '#locals' do it 'returns the locals hash, as is' do j = @scheduler.schedule_in '1s', locals: { a: :aa, b: :bb } do; end expect(j.locals).to eq(a: :aa, b: :bb) 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 wait_until { job.threads.size > 0 } 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 wait_until { j0.threads.size + j1.threads.size > 0 } 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) } wait_until { j0.threads.size + j1.threads.size > 0 } 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 wait_until { j0.threads.size + j1.threads.size > 0 } 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 #wait_until { $stderr.string.match?(/Rufus::Scheduler::TimeoutError/) } # no worky on older Rubies... so wait_until { $stderr.string.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 wait_until { counter > 1 } end end context 'discard_past: true/false' do # specified in spec/job_repeat_spec.rb end context 'name: / n:' do it 'sets the job name' do j0 = @scheduler.schedule_in '10d', name: 'Alfred' do; end j1 = @scheduler.schedule_in '11d', n: 'Alberich' do; end expect(j0.name).to eq('Alfred') expect(j1.name).to eq('Alberich') 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.0999 expect(job.mean_work_time).to be > 0.05 expect(job.mean_work_time).to be < 0.07 end end end context 'one time job' do describe '#determine_id' do it 'returns unique ids' do ids = {} 10_000.times do id = @scheduler.in('1y') {} break if ids[id] ids[id] = true end expect(ids.length).to eq(10_000) end end end context 'repeat job' do describe '#determine_id' do it 'returns unique ids' do ids = {} 10_000.times do id = @scheduler.every('1y') {} break if ids[id] ids[id] = true end expect(ids.length).to eq(10_000) end end end end rufus-scheduler-3.8.0/spec/lock_custom_spec.rb000066400000000000000000000011661407342460500214660ustar00rootroot00000000000000 # # 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.8.0/spec/lock_flock_spec.rb000066400000000000000000000013751407342460500212540ustar00rootroot00000000000000 # # 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.8.0/spec/lock_lockfile_spec.rb000066400000000000000000000024301407342460500217370ustar00rootroot00000000000000 # # 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.8.0/spec/lock_spec.rb000066400000000000000000000023701407342460500200720ustar00rootroot00000000000000 # # 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.8.0/spec/parse_spec.rb000066400000000000000000000153741407342460500202640ustar00rootroot00000000000000 # # 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 def paus(s); Rufus::Scheduler.parse(s).getutc.strftime('%c'); 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( paus('Sun Nov 18 16:01:00 2012 Asia/Singapore') ).to eq('Sun Nov 18 08:01:00 2012') expect( paus('Sun Nov 18 16:01:00 2012 Zulu') ).to eq('Sun Nov 18 16:01:00 2012') expect( paus('Sun Nov 18 16:01:00 Asia/Singapore 2012') ).to eq('Sun Nov 18 08:01:00 2012') expect( paus('Asia/Singapore Sun Nov 18 16:01:00 2012') ).to eq('Sun Nov 18 08:01:00 2012') expect( paus('Sun Nov 18 16:01:00 2012 America/New_York') ).to eq('Sun Nov 18 21:01:00 2012') 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 implicitly)' do #dump_zones #localzone = Time.now.strftime('%z') #localzone = 'Z' if localzone == '+0000' #expect( # pa('Nov 18 16:01:00 2012').strftime('%c %z') #).to eq("Sun Nov 18 16:01:00 2012 #{localzone}") expect( pa('Nov 18 16:01:00 2012').strftime('%c %z') .gsub(' +0000', ' Z') ).to eq('Sun Nov 18 16:01:00 2012 Z') end it 'parses cronlines' do out = pa('* * * * *') expect(out.class).to eq(Fugit::Cron) expect(out.original).to eq('* * * * *') expect(pa('10 23 * * *').class).to eq(Fugit::Cron) expect(pa('* 23 * * *').class).to eq(Fugit::Cron) end it 'raises on unparseable input' do expect { pa('nada') }.to raise_error( ArgumentError, 'couldn\'t parse "nada" (String)' ) 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.s')).to eq(-5.0) expect(pd('-2.5s')).to eq(-2.5) expect(pd('-1s')).to eq(-1.0) expect(pd('-500s')).to eq(-500) expect(pd('')).to eq(0.0) expect(pd('5.0s')).to eq(5.0) expect(pd('0.5s')).to eq(0.5) expect(pd('.5s')).to eq(0.5) expect(pd('5.s')).to eq(5.0) expect(pd('500s')).to eq(500) expect(pd('1000s')).to eq(1000) 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) 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 [ '-', 'h', 'whatever', 'hms', Time.now ].each do |x| expect { Rufus::Scheduler.parse_duration(x) }.to raise_error(ArgumentError) end # not since .parse_duration rewrite #expect { pd(' 1h ') }.to raise_error(ArgumentError) end it 'returns nil on unreadable duration when no_error: true' do [ '-', 'h', 'whatever', 'hms', Time.now ].each do |x| expect(Rufus::Scheduler.parse_duration(x, :no_error => true)).to eq(nil) end end end describe '.parse_cron' do it 'parses a cron string' do c = Rufus::Scheduler.parse_cron('23 0-23/2 * * *') expect(c).to be_a(Fugit::Cron) expect(c.hours).to eq((0..22).step(2).to_a) end it 'fails on non cron string' do expect { Rufus::Scheduler.parse_cron('nada 23 0-23/2 * * *') }.to raise_error( ArgumentError, 'invalid cron string "nada 23 0-23/2 * * *"' ) end it 'returns nil on cron string when no_error: true' do expect( Rufus::Scheduler.parse_cron('nada 23 0-23/2 * * *', no_error: true) ).to eq(nil) 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('0.1s') expect(td(1.1)).to eq('1.1s') end end describe '.to_duration_hash' do [ [ 0, nil, { :s => 0 } ], [ 60, nil, { :m => 1 } ], [ 0.128, nil, { :s => 0.128 } ], [ 60.127, nil, { :m => 1, :s => 0.127 } ], [ 61.127, nil, { :m => 1, :s => 1.127 } ], [ 61.127, { :drop_seconds => true }, { :m => 1 } ], ].each do |f, o, h| # float, options, hash it "turns #{f.inspect} into #{h.inspect} #{o ? "(#{o.inspect})" : ''}" do expect(Rufus::Scheduler.to_duration_hash(f, o || {})).to eq(h) end end end end rufus-scheduler-3.8.0/spec/schedule_at_spec.rb000066400000000000000000000065031407342460500214240ustar00rootroot00000000000000 # # 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_f).to eq(t.to_f) 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_f).to eq(t.to_f) end it 'accepts a time string' do job = @scheduler.at('2100-12-12 20:30', :job => true) {} jt = job.time expect(jt.zone).to eq(EtOrbi::EoTime.local_tzone) expect(jt.strftime('%Y-%m-%d %H:%M:%S')).to eq('2100-12-12 20:30:00') 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.strftime('%Y-%m-%d %H:%M:%S %:z') ).to eq( '2100-12-12 20:30:00 -02:00' ) 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.8.0/spec/schedule_cron_spec.rb000066400000000000000000000045531407342460500217640ustar00rootroot00000000000000 # # 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 'accepts a CronLine instance' do cl = Fugit.parse('* * * * *') job_id = @scheduler.cron(cl) {} job = @scheduler.job(job_id) expect(job.cron_line.object_id).to eq(cl.object_id) end it 'is not slow handling frequent cron durations' do @scheduler.frequency = 10 s = Time.now @scheduler.cron '*/15 * * * * *' do; end expect(Time.now - s).to be < 1 end it 'is not slow handling non-frequent cron durations' do @scheduler.frequency = 10 s = Time.now @scheduler.cron '31 18 18 10 *' do; end expect(Time.now - s).to be < 1 end it 'fails if the job frequency is higher than the scheduler frequency' do @scheduler.frequency = 10 expect { @scheduler.cron '* * * * * *' do; end }.to raise_error( ArgumentError, 'job frequency (min ~1s) is higher than scheduler frequency (10s)' ) end it 'fails if the cron line is invalid' do # gh-289 expect { @scheduler.cron '/hell * * * *' do; end }.to raise_error( ArgumentError, 'invalid cron string "/hell * * * *"' ) 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 it 'accepts a CronLine instance' do cl = Fugit.parse('* * * * *') job = @scheduler.schedule_cron(cl) {} expect(job.cron_line.object_id).to eq(cl.object_id) end end end rufus-scheduler-3.8.0/spec/schedule_every_spec.rb000066400000000000000000000033731407342460500221540ustar00rootroot00000000000000 # # 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.8.0/spec/schedule_in_spec.rb000066400000000000000000000024671407342460500214330ustar00rootroot00000000000000 # # 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.8.0/spec/schedule_interval_spec.rb000066400000000000000000000043751407342460500226510ustar00rootroot00000000000000 # # 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.8.0/spec/schedule_spec.rb000066400000000000000000000023761407342460500207440ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Sat Aug 13 21:00:31 JST 2016 # require 'spec_helper' describe Rufus::Scheduler do before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown end describe '#schedule' do it 'leaves the schedule option hash untouched (2 args)' do opts = { :x => :y } job = @scheduler.schedule('1s', opts) {} expect(opts.size).to eq(1) end it 'leaves the schedule option hash untouched (3 args)' do opts = { :x => :y } callable = lambda {} job = @scheduler.schedule('1s', callable, opts) expect(opts.size).to eq(1) end it 'accepts a CronLine instance' do cl = Fugit.parse('* * * * *') job = @scheduler.schedule(cl) {} expect(job.cron_line.object_id).to eq(cl.object_id) end end describe '#at' do it 'leaves the schedule option hash untouched (2 args)' do opts = { :x => :y } job = @scheduler.at(Time.now + 10, opts) {} expect(opts.size).to eq(1) end it 'leaves the schedule option hash untouched (3 args)' do opts = { :x => :y } callable = lambda {} job = @scheduler.at(Time.now + 10, callable, opts) expect(opts.size).to eq(1) end end end rufus-scheduler-3.8.0/spec/scheduler_spec.rb000066400000000000000000000711731407342460500211270ustar00rootroot00000000000000 # # 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: 2 (int) 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 it 'accepts a discard_past: option' do scheduler = Rufus::Scheduler.new expect(scheduler.discard_past).to eq(true) scheduler = Rufus::Scheduler.new(discard_past: false) expect(scheduler.discard_past).to eq(false) end end before :each do @scheduler = Rufus::Scheduler.new end after :each do @scheduler.shutdown if @scheduler.uptime # don't shutdown an already shut down scheduler. 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 } wait_until { j } 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 } wait_until { t } expect(t.class).to eq(EtOrbi::EoTime) 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) wait_until { mh.counter > 0 } 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) wait_until { job.handler.counter > 0 } 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) wait_until { job.handler.value } 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 } wait_until { seen } end it 'accepts point in time and duration indifferently (#at)' do seen = false t = 1 @scheduler.at(t) { seen = true } wait_until { seen } 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(/\A[12]\.\d+s\z/) 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 '#join(limit)' do it 'joins the scheduler thread' do t = Thread.new do Thread.current['r'] = @scheduler.join(1) Thread.current['a'] = 'over' end expect(t['r']).to eq(nil) expect(t['a']).to eq(nil) @scheduler.shutdown sleep(1) expect(t['r'].class).to eq(Thread) expect(t['a']).to eq('over') end it 'times out' do a = [] @scheduler.in(0.010) do a << 0 sleep 3 a << 1 end t0 = monow r = @scheduler.join(1) expect(monow - t0).to be < 1.5 expect(a).to eq([ 0 ]) expect(r).to eq(nil) 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 wait_until { @scheduler.threads.size == 2 } 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 wait_until { @scheduler.work_threads(:active).size >= 1 } 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 wait_until { @scheduler.work_threads(:active).empty? } 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 wait_until { @scheduler.running_jobs.size >= 1 } 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 wait_until { @scheduler.running_jobs.size >= 1 } 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 wait_until { @scheduler.running_jobs.size > 1 } 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 seen = false job = @scheduler.schedule_in '0s' do sleep 1 seen = true end wait_until { job.threads.first } expect(seen).to eq(false) @scheduler.shutdown(:wait) expect(seen).to eq(true) expect(@scheduler.uptime).to eq(nil) expect(@scheduler.running_jobs).to eq([]) expect(@scheduler.threads).to eq([]) end it 'does not mind being called from a scheduler job (gh-304)' do seen = [] job0 = @scheduler.schedule_in '0s' do seen << :job0a sleep 3 seen << :job0b end sleep 0.300 job1 = @scheduler.schedule_in '0s' do seen << :job1a @scheduler.shutdown(:wait) seen << :job1b end t0 = monow wait_until { @scheduler.uptime == nil } expect(monow - t0).to be_between(2.5, 4.0) expect(seen.take(3)).to eq([ :job0a, :job1a, :job0b ]) wait_until { @scheduler.threads == [] } end end describe '#shutdown(wait: n)' do it 'waits no more than n seconds' do seen = [] job0 = @scheduler.schedule_in '0s' do seen << :job0a sleep 100 seen << :job0b end sleep 0.300 job1 = @scheduler.schedule_in '0s' do seen << :job1a sleep 4 seen << :job1b end wait_until { seen.include?(:job1a) } expect(seen).to eq([ :job0a, :job1a ]) t0 = monow @scheduler.shutdown(wait: 2) expect(monow - t0).to be_between(2.0, 3.0) expect(job0.threads.size).to eq(0) expect(job1.threads.size).to eq(0) expect(@scheduler.uptime).to eq(nil) expect(@scheduler.running_jobs).to eq([]) expect(@scheduler.threads).to eq([]) end it 'does not mind being called from a scheduler job (gh-304)' do seen = [] job0 = @scheduler.schedule_in '0s' do seen << :job0a sleep 5 seen << :job0b end sleep 0.300 job1 = @scheduler.schedule_in '0s' do seen << :job1a t0 = monow @scheduler.shutdown(wait: 2) seen << (monow - t0) end wait_until { seen.size > 2 } expect(seen[0, 2]).to eq([ :job0a, :job1a ]) expect(seen[2]).to be_between(2.0, 3.0) expect(@scheduler.uptime).to eq(nil) expect(@scheduler.running_jobs).to eq([]) wait_until { @scheduler.threads == [] } 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) wait_until { @scheduler.threads.empty? } expect(counter).to eq(0) expect(@scheduler.uptime).to eq(nil) expect(@scheduler.running_jobs).to eq([]) expect(@scheduler.threads).to eq([]) 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 it 'does not mind being called from a scheduler job (gh-304)' do seen = [] job0 = @scheduler.schedule_in '0s' do seen << :job0a sleep 5 seen << :job0b end sleep 0.300 job1 = @scheduler.schedule_in '0s' do seen << :job1a @scheduler.shutdown(:kill) seen << :job1b end wait_until { seen.include?(:job1a) } expect(@scheduler.uptime).to eq(nil) wait_until { @scheduler.running_jobs.empty? } wait_until { @scheduler.threads == [] } 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 context 'discard_past:' do context 'by default' do it 'discards the past' do #@scheduler.discard_past = true # this is the default job = @scheduler.schedule_every('1s') do; end @scheduler.pause expect(job.count).to eq(0) sleep 2 @scheduler.resume wait_until { job.count > 0 } expect(job.count).to eq(1) end end context 'false' do it 'prevents discarding the past' do #@scheduler.discard_past = true # this is the default job = @scheduler.schedule_every('1s') do; end @scheduler.pause expect(job.count).to eq(0) sleep 2 @scheduler.resume(discard_past: false) wait_until { job.count > 1 } end end 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 wait_until { @scheduler.jobs.size > 0 } 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 wait_until { $out.size > 1 } 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 wait_until { $tt } expect($tt.class).to eq(EtOrbi::EoTime) 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 wait_until { $out.size > 0 } 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 wait_until { $out.size > 1 } expect($out).to eq([ job_id, "post #{job_id}" ]) end end describe '#around_trigger' do it 'functions normally if no around_trigger is defined' do $out = [] job_id = @scheduler.in '0.5s' do |job| $out << job.id end wait_until { $out.size > 0 } expect($out).to eq([ job_id ]) end it 'wraps the job' do $out = [] def @scheduler.around_trigger(job) $out << "pre #{job.id}" yield $out << "post #{job.id}" end job_id = @scheduler.in '0.5s' do |job| $out << job.id end wait_until { $out.size > 2 } expect($out).to eq([ "pre #{job_id}", job_id, "post #{job_id}" ]) end it 'does not block (runs in job thread)' do $out = [] def @scheduler.around_trigger(job) $out << "pre #{job.id}" yield $out << "post #{job.id}" end # using Thread.pass to space out job scheduling/triggering # so that $out.take(3) becomes predictable job_id1 = @scheduler.in '0.1s' do |job| sleep 0.5 $out << job.id end Thread.pass job_id2 = @scheduler.in '0.2s' do |job| Thread.pass $out << job.id end wait_until { $out.size > 2 } expect($out.take(3)).to eq([ "pre #{job_id1}", "pre #{job_id2}", job_id2 ]) 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.8.0/spec/spec_helper.rb000066400000000000000000000102371407342460500204220ustar00rootroot00000000000000 # # Specifying rufus-scheduler # # Wed Apr 17 06:00:59 JST 2013 # require 'pp' Thread.abort_on_exception = true require 'stringio' require 'rufus-scheduler' puts puts __FILE__ puts puts "RUBY_VERSION => #{RUBY_VERSION.inspect}" puts "RUBY_PLATFORM => #{RUBY_PLATFORM.inspect}" puts def dump_zones puts "*" * 80 puts "ENV['TZ'] => #{ENV['TZ'].inspect}" puts "Time.now.zone => #{Time.now.zone.inspect}" puts "Time.now.strftime('%z') => #{Time.now.strftime('%z').inspect}" puts "EtOrbi::VERSION => #{EtOrbi::VERSION.inspect}" puts "EtOrbi::EoTime.now.zone => #{EtOrbi::EoTime.now.zone.inspect}" puts "EtOrbi::EoTime.now.strftime('%z') => #{EtOrbi::EoTime.now.strftime('%z').inspect}" puts "EtOrbi::EoTime.local_tzone => #{EtOrbi::EoTime.local_tzone.inspect}" puts "EtOrbi::EoTime.local_tzone.name => #{EtOrbi::EoTime.local_tzone.name.inspect}" puts "*" * 80 end dump_zones puts # # misc helper methods module Helpers 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 zlocal(*args) EtOrbi::EoTime.new(Time.local(*args).to_f, nil) end alias zlo zlocal def utc(*args) Time.utc(*args) end def zutc(*args) EtOrbi::EoTime.new(Time.utc(*args), 'Zulu') 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 ztz(tz, *args) EtOrbi::EoTime.new(Time.local(*args), tz) end def ztu(tz, *args) EtOrbi::EoTime.new(Time.utc(*args), tz) 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 def wait_until(timeout=14, frequency=0.1, &block) start = monow loop do sleep(frequency) #return if block.call == true r = block.call return r if r break if monow - start > timeout end fail "timeout after #{timeout}s" end alias :wait_for :wait_until def wait_next_seconds(i=1) s0 = Time.now.sec wait_until(14, 0.05) do s1 = Time.now.sec s1 += 60 if s1 < s0 s1 - s0 == i end i end alias :wait_next_second :wait_next_seconds def monow; Rufus::Scheduler.monow; end def ltstamp; Rufus::Scheduler.ltstamp; end if RUBY_VERSION > '1.9.9' def tstamp Time.now.strftime('%T.%6N') end else def tstamp t = Time.now; "#{t.strftime('%H:%M:%S')}.#{sprintf('%06d', t.usec)}" end end end RSpec.configure { |c| c.include(Helpers) } class Time def to_debug_s uo = self.utc_offset uos = uo < 0 ? '-' : '+' uo = uo.abs uoh, uom = [ uo / 3600, uo % 3600 ] [ 't', self.strftime('%Y-%m-%d %H:%M:%S'), "%s%02d:%02d" % [ uos, uoh, uom ], "dst:#{self.isdst}" ].join(' ') end end class TZInfo::Timezone def _name case name when /UTC\z/ then 'UTC' else name end end end # # matchers #require 'rspec/expectations' RSpec::Matchers.define :be_within_1s_of do |expected, suffix| 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}" + (suffix ? ' ' + suffix : '') else "expected a EoTime instance, got a #{actual.inspect}" end end end # # configure #RSpec.configure do |config| #end rufus-scheduler-3.8.0/spec/threads_spec.rb000066400000000000000000000033101407342460500205670ustar00rootroot00000000000000 # # 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