rufus-scheduler 2.0.24 → 3.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (53) hide show
  1. data/CHANGELOG.txt +6 -0
  2. data/CREDITS.txt +4 -0
  3. data/README.md +1064 -0
  4. data/Rakefile +1 -4
  5. data/TODO.txt +145 -55
  6. data/lib/rufus/scheduler.rb +502 -26
  7. data/lib/rufus/{sc → scheduler}/cronline.rb +46 -17
  8. data/lib/rufus/{sc/version.rb → scheduler/job_array.rb} +56 -4
  9. data/lib/rufus/scheduler/jobs.rb +548 -0
  10. data/lib/rufus/scheduler/util.rb +318 -0
  11. data/rufus-scheduler.gemspec +30 -4
  12. data/spec/cronline_spec.rb +29 -8
  13. data/spec/error_spec.rb +116 -0
  14. data/spec/job_array_spec.rb +39 -0
  15. data/spec/job_at_spec.rb +58 -0
  16. data/spec/job_cron_spec.rb +67 -0
  17. data/spec/job_every_spec.rb +71 -0
  18. data/spec/job_in_spec.rb +20 -0
  19. data/spec/job_interval_spec.rb +68 -0
  20. data/spec/job_repeat_spec.rb +308 -0
  21. data/spec/job_spec.rb +387 -115
  22. data/spec/lockfile_spec.rb +61 -0
  23. data/spec/parse_spec.rb +203 -0
  24. data/spec/schedule_at_spec.rb +129 -0
  25. data/spec/schedule_cron_spec.rb +66 -0
  26. data/spec/schedule_every_spec.rb +109 -0
  27. data/spec/schedule_in_spec.rb +80 -0
  28. data/spec/schedule_interval_spec.rb +128 -0
  29. data/spec/scheduler_spec.rb +831 -124
  30. data/spec/spec_helper.rb +65 -0
  31. data/spec/threads_spec.rb +75 -0
  32. metadata +64 -59
  33. data/README.rdoc +0 -661
  34. data/lib/rufus/otime.rb +0 -3
  35. data/lib/rufus/sc/jobqueues.rb +0 -160
  36. data/lib/rufus/sc/jobs.rb +0 -471
  37. data/lib/rufus/sc/rtime.rb +0 -363
  38. data/lib/rufus/sc/scheduler.rb +0 -636
  39. data/spec/at_in_spec.rb +0 -47
  40. data/spec/at_spec.rb +0 -125
  41. data/spec/blocking_spec.rb +0 -64
  42. data/spec/cron_spec.rb +0 -134
  43. data/spec/every_spec.rb +0 -304
  44. data/spec/exception_spec.rb +0 -113
  45. data/spec/in_spec.rb +0 -150
  46. data/spec/mutex_spec.rb +0 -159
  47. data/spec/rtime_spec.rb +0 -137
  48. data/spec/schedulable_spec.rb +0 -97
  49. data/spec/spec_base.rb +0 -87
  50. data/spec/stress_schedule_unschedule_spec.rb +0 -159
  51. data/spec/timeout_spec.rb +0 -148
  52. data/test/kjw.rb +0 -113
  53. data/test/t.rb +0 -20
data/CHANGELOG.txt CHANGED
@@ -2,6 +2,12 @@
2
2
  = rufus-scheduler CHANGELOG.txt
3
3
 
4
4
 
5
+ == rufus-scheduler - 3.0.0 released 2013/10/02
6
+
7
+ - complete rewrite.
8
+ - introduce scheduler.interval('10s') { ... }
9
+
10
+
5
11
  == rufus-scheduler - 2.0.24 released 2013/09/02
6
12
 
7
13
  - lowered tzinfo dependency to >= 0.3.22
data/CREDITS.txt CHANGED
@@ -5,6 +5,7 @@
5
5
  == Contributors
6
6
 
7
7
  - Tobias Kraze (https://github.com/kratob) timeout vs mutex fix
8
+ - Patrick Farrell (https://github.com/pfarrell) pointing at deprecated start_new
8
9
  - Thomas Sevestre (https://github.com/thomassevestre) :exception option
9
10
  - Matteo Cerutti - last_time / previous_time idea (and initial implementation)
10
11
  - Aimee Rose (https://github.com/AimeeRose) cronline and > 24
@@ -26,6 +27,9 @@
26
27
 
27
28
  == Feedback
28
29
 
30
+ - Kevin Bouwkamp - https://github.com/bmxpert1 - first_at issues
31
+ - Daniel Beauchamp - https://github.com/pushmatrix - pre/post trigger callbacks
32
+ - Arthur Maltson - https://github.com/amaltson - readme fixes
29
33
  - skrd - https://github.com/skrd - "/10 * * * *" cron issue
30
34
  - Hongli Lai - Scheduler#stop(:terminate => true) request
31
35
  - Tero Tilus - raises on unsupported/unknown options
data/README.md ADDED
@@ -0,0 +1,1064 @@
1
+
2
+ # rufus-scheduler
3
+
4
+ [![Build Status](https://secure.travis-ci.org/jmettraux/rufus-scheduler.png)](http://travis-ci.org/jmettraux/rufus-scheduler)
5
+
6
+ Job scheduler for Ruby (at, cron, in and every jobs).
7
+
8
+ **Note**: maybe are you looking for the [README of rufus-scheduler 2.x](https://github.com/jmettraux/rufus-scheduler/blob/two/README.rdoc)?
9
+
10
+ Quickstart:
11
+ ```ruby
12
+ require 'rufus-scheduler'
13
+
14
+ scheduler = Rufus::Scheduler.new
15
+
16
+ scheduler.in '3s' do
17
+ puts 'Hello... Rufus'
18
+ end
19
+
20
+ scheduler.join
21
+ # let the current thread join the scheduler thread
22
+ ```
23
+
24
+ Various forms of scheduling are supported:
25
+ ```ruby
26
+ require 'rufus-scheduler'
27
+
28
+ scheduler = Rufus::Scheduler.new
29
+
30
+ # ...
31
+
32
+ scheduler.in '10d' do
33
+ # do something in 10 days
34
+ end
35
+
36
+ scheduler.at '2030/12/12 23:30:00' do
37
+ # do something at a given point in time
38
+ end
39
+
40
+ scheduler.every '3h' do
41
+ # do something every 3 hours
42
+ end
43
+
44
+ scheduler.cron '5 0 * * *' do
45
+ # do something every day, five minutes after midnight
46
+ # (see "man 5 crontab" in your terminal)
47
+ end
48
+
49
+ # ...
50
+ ```
51
+
52
+ ## non-features
53
+
54
+ Rufus-scheduler (out of the box) is an in-process, in-memory scheduler.
55
+
56
+ It does not persist your schedules. When the process is gone and the scheduler instance with it, the schedules are gone.
57
+
58
+
59
+ ## related and similar gems
60
+
61
+ * [whenever](https://github.com/javan/whenever) - let cron call back your Ruby code, trusted and reliable cron drives your schedule
62
+ * [clockwork](https://github.com/tomykaira/clockwork) - rufus-scheduler inspired gem
63
+
64
+ (please note: rufus-scheduler is not a cron replacement)
65
+
66
+
67
+ ## note about the 3.0 line
68
+
69
+ It's a complete rewrite of rufus-scheduler.
70
+
71
+ There is no EventMachine-based scheduler anymore.
72
+
73
+
74
+ ## Notables changes:
75
+
76
+ * As said, no more EventMachine-based scheduler
77
+ * ```scheduler.every('100') {``` will schedule every 100 seconds (previously, it would have been 0.1s). This aligns rufus-scheduler on Ruby's ```sleep(100)```
78
+ * The scheduler isn't catching the whole of Exception anymore, only StandardError
79
+ * The error_handler is #on_error (instead of #on_exception), by default it now prints the details of the error to $stderr (used to be $stdout)
80
+ * Rufus::Scheduler::TimeOutError renamed to Rufus::Scheduler::TimeoutError
81
+ * Introduction of "interval" jobs. Whereas "every" jobs are like "every 10 minuts, do this", interval jobs are like "do that, then wait for 10 minutes, then do that again, and so on"
82
+ * Introduction of a :lockfile => true/filename mechanism to prevent multiple schedulers from executing
83
+ * "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.
84
+ * Introduction of Scheduler #on_pre_trigger and #on_post_trigger callback points
85
+
86
+
87
+ ## getting help
88
+
89
+ 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.
90
+
91
+ Go read [how to report bugs effectively](http://www.chiark.greenend.org.uk/~sgtatham/bugs.html), twice.
92
+
93
+ Update: [help_help.md](https://gist.github.com/jmettraux/310fed75f568fd731814) might help help you.
94
+
95
+ ### on StackOverflow
96
+
97
+ Use this [form](http://stackoverflow.com/questions/ask?tags=rufus-scheduler+ruby). It'll create a question flagged "rufus-scheduler" and "ruby".
98
+
99
+ Here are the [questions tagged rufus-scheduler](http://stackoverflow.com/questions/tagged/rufus-scheduler).
100
+
101
+ ### on IRC
102
+
103
+ I sometimes haunt #ruote on freenode.net. The channel is not dedicated to rufus-scheduler, so if you ask a question, first mention it's about rufus-scheduler.
104
+
105
+ Please note that I prefer helping over Stack Overflow because it's more searchable than the ruote IRC archive.
106
+
107
+ ### issues
108
+
109
+ Yes, issues can be reported in [rufus-scheduler issues](https://github.com/jmettraux/rufus-scheduler/issues), I'd actually prefer bugs in there. If there is nothing wrong with rufus-scheduler, a [Stack Overflow question](http://stackoverflow.com/questions/ask?tags=rufus-scheduler+ruby) is better.
110
+
111
+ ### faq
112
+
113
+ * [It doesn't work...](http://www.chiark.greenend.org.uk/~sgtatham/bugs.html)
114
+ * [I want a refund](http://blog.nodejitsu.com/getting-refunds-on-open-source-projects)
115
+ * [Passenger and rufus-scheduler](http://stackoverflow.com/questions/18108719/debugging-rufus-scheduler/18156180#18156180)
116
+
117
+
118
+ ## scheduling
119
+
120
+ Rufus-scheduler supports five kinds of jobs. in, at, every, interval and cron jobs.
121
+
122
+ Most of the rufus-scheduler examples show block scheduling, but it's also OK to schedule handler instances or handler classes.
123
+
124
+ ### in, at, every, interval, cron
125
+
126
+ In and at jobs trigger once.
127
+
128
+ ```ruby
129
+ require 'rufus-scheduler'
130
+
131
+ scheduler = Rufus::Scheduler.new
132
+
133
+ scheduler.in '10d' do
134
+ puts "10 days reminder for review X!"
135
+ end
136
+
137
+ scheduler.at '2014/12/24 2000' do
138
+ puts "merry xmas!"
139
+ end
140
+ ```
141
+
142
+ 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).
143
+
144
+ Every, interval and cron jobs trigger repeatedly.
145
+
146
+ ```ruby
147
+ require 'rufus-scheduler'
148
+
149
+ scheduler = Rufus::Scheduler.new
150
+
151
+ scheduler.every '3h' do
152
+ puts "change the oil filter!"
153
+ end
154
+
155
+ scheduler.interval '2h' do
156
+ puts "thinking..."
157
+ puts sleep(rand * 1000)
158
+ puts "thought."
159
+ end
160
+
161
+ scheduler.cron '00 09 * * *' do
162
+ puts "it's 9am! good morning!"
163
+ end
164
+ ```
165
+
166
+ Every jobs try hard to trigger following the frequency they were scheduled with.
167
+
168
+ 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).
169
+
170
+ 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.
171
+
172
+ ### #schedule_x vs #x
173
+
174
+ schedule_in, schedule_at, schedule_cron, etc will return the new Job instance.
175
+
176
+ in, at, cron will return the new Job instance's id (a String).
177
+
178
+ ```ruby
179
+ job_id =
180
+ scheduler.in '10d' do
181
+ # ...
182
+ end
183
+ job = scheduler.job(job_id)
184
+
185
+ # versus
186
+
187
+ job =
188
+ scheduler.schedule_in '10d' do
189
+ # ...
190
+ end
191
+
192
+ # also
193
+
194
+ job =
195
+ scheduler.in '10d', :job => true do
196
+ # ...
197
+ end
198
+ ```
199
+
200
+ ### #schedule and #repeat
201
+
202
+ Sometimes it pays to be less verbose.
203
+
204
+ The ```#schedule``` methods schedules an at, in or cron job. It just decide based on its input. It returns the Job instance.
205
+
206
+ ```ruby
207
+ scheduler.schedule '10d' do; end.class
208
+ # => Rufus::Scheduler::InJob
209
+
210
+ scheduler.schedule '2013/12/12 12:30' do; end.class
211
+ # => Rufus::Scheduler::AtJob
212
+
213
+ scheduler.schedule '* * * * *' do; end.class
214
+ # => Rufus::Scheduler::CronJob
215
+ ```
216
+
217
+ The ```#repeat``` method schedules and returns an EveryJob or a CronJob.
218
+
219
+ ```ruby
220
+ scheduler.repeat '10d' do; end.class
221
+ # => Rufus::Scheduler::EveryJob
222
+
223
+ scheduler.repeat '* * * * *' do; end.class
224
+ # => Rufus::Scheduler::CronJob
225
+ ```
226
+
227
+ (Yes, no combination heres gives back an IntervalJob).
228
+
229
+ ### schedule blocks arguments (job, time)
230
+
231
+ A schedule block may be given 0, 1 or 2 arguments.
232
+
233
+ The first argument is "job", it's simple the Job instance involved. It might be useful if the job is to be unscheduled for some reason.
234
+
235
+ ```ruby
236
+ scheduler.every '10m' do |job|
237
+
238
+ status = determine_pie_status
239
+
240
+ if status == 'burnt' || status == 'cooked'
241
+ stop_oven
242
+ takeout_pie
243
+ job.unschedule
244
+ end
245
+ end
246
+ ```
247
+
248
+ The second argument is "time", it's the time when the job got cleared for triggering (not Time.now).
249
+
250
+ Note that time is the time when the job got cleared for triggering. If there are mutexes involved, now = mutex_wait_time + time...
251
+
252
+ ### scheduling handler instances
253
+
254
+ It's OK to pass any object, as long as it respond to #call(), when scheduling:
255
+
256
+ ```ruby
257
+ class Handler
258
+ def self.call(job, time)
259
+ p "- Handler called for #{job.id} at #{time}"
260
+ end
261
+ end
262
+
263
+ scheduler.in '10d', Handler
264
+
265
+ # or
266
+
267
+ class OtherHandler
268
+ def initialize(name)
269
+ @name = name
270
+ end
271
+ def call(job, time)
272
+ p "* #{time} - Handler #{name.inspect} called for #{job.id}"
273
+ end
274
+ end
275
+
276
+ oh = OtherHandler.new('Doe')
277
+
278
+ scheduler.every '10m', oh
279
+ scheduler.in '3d5m', oh
280
+ ```
281
+
282
+ The call method must accept 2 (job, time), 1 (job) or 0 arguments.
283
+
284
+ Note that time is the time when the job got cleared for triggering. If there are mutexes involved, now = mutex_wait_time + time...
285
+
286
+ ### scheduling handler classes
287
+
288
+ One can pass a handler class to rufus-scheduler when scheduling. Rufus will instantiate it and that instance will be available via job#handler.
289
+
290
+ ```ruby
291
+ class MyHandler
292
+ attr_reader :count
293
+ def initialize
294
+ @count = 0
295
+ end
296
+ def call(job)
297
+ @count += 1
298
+ puts ". #{self.class} called at #{Time.now} (#{@count})"
299
+ end
300
+ end
301
+
302
+ job = scheduler.schedule_every '35m', MyHandler
303
+
304
+ job.handler
305
+ # => #<MyHandler:0x000000021034f0>
306
+ job.handler.count
307
+ # => 0
308
+ ```
309
+
310
+ If you want to keep that "block feeling":
311
+
312
+ ```ruby
313
+ job_id =
314
+ scheduler.every '10m', Class.new do
315
+ def call(job)
316
+ puts ". hello #{self.inspect} at #{Time.now}"
317
+ end
318
+ end
319
+ ```
320
+
321
+
322
+ ## pause and resume the scheduler
323
+
324
+ The scheduler can be paused via the #pause and #resume methods. One can determine if the scheduler is currently paused by calling #paused?.
325
+
326
+ While paused, the scheduler still accepts schedules, but no schedule will get triggered as long as #resume isn't called.
327
+
328
+
329
+ ## job options
330
+
331
+ ### :blocking => true
332
+
333
+ By default, jobs are triggered in their own, new thread. When :blocking => true, the job is triggered in the scheduler thread (a new thread is not created). Yes, while the job triggers, the scheduler is not scheduling.
334
+
335
+ ### :overlap => false
336
+
337
+ Since, by default, jobs are triggered in their own new thread, job instances might overlap. For example, a job that takes 10 minutes and is scheduled every 7 minutes will have overlaps.
338
+
339
+ To prevent overlap, one can set :overlap => false. Such a job will not trigger if one of its instance is already running.
340
+
341
+ ### :mutex => mutex_instance / mutex_name / array of mutexes
342
+
343
+ When a job with a mutex triggers, the job's block is executed with the mutex around it, preventing other jobs with the same mutex to enter (it makes the other jobs wait until it exits the mutex).
344
+
345
+ 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.
346
+
347
+ :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.
348
+
349
+ Array of mutexes: original idea and implementation by [Rainux Luo](https://github.com/rainux)
350
+
351
+ Warning: creating lots of different mutexes is OK. Rufus-scheduler will place them in its Scheduler#mutexes hash... And they won't get garbage collected.
352
+
353
+ ### :timeout => duration or point in time
354
+
355
+ It's OK to specify a timeout when scheduling some work. After the time specified, it gets interrupted via a Rufus::Scheduler::TimeoutError.
356
+
357
+ ```ruby
358
+ scheduler.in '10d', :timeout => '1d' do
359
+ begin
360
+ # ... do something
361
+ rescue Rufus::Scheduler::TimeoutError
362
+ # ... that something got interrupted after 1 day
363
+ end
364
+ end
365
+ ```
366
+
367
+ The :timeout option accepts either a duration (like "1d" or "2w3d") or a point in time (like "2013/12/12 12:00").
368
+
369
+ ### :first_at, :first_in, :first
370
+
371
+ This option is for repeat jobs (cron / every) only.
372
+
373
+ It's used to specify the first time after which the repeat job should trigger for the first time.
374
+
375
+ In the case of an "every" job, this will be the first time (module the scheduler frequency) the job triggers.
376
+ For a "cron" job, it's the time after which the first schedule will trigger.
377
+
378
+ ```ruby
379
+ scheduler.every '2d', :first_at => Time.now + 10 * 3600 do
380
+ # ... every two days, but start in 10 hours
381
+ end
382
+
383
+ scheduler.every '2d', :first_in => '10h' do
384
+ # ... every two days, but start in 10 hours
385
+ end
386
+ ```
387
+
388
+ :first, :first_at and :first_in all accept a point in time or a duration (number or time string). Use the symbol you think make your schedule more readable.
389
+
390
+ Note: it's OK to change the first_at (a Time instance) directly:
391
+ ```ruby
392
+ job.first_at = Time.now + 10
393
+ job.first_at = Rufus::Scheduler.parse('2029-12-12')
394
+ ```
395
+
396
+ ### :last_at, :last_in, :last
397
+
398
+ This option is for repeat jobs (cron / every) only.
399
+
400
+ It indicates the point in time after which the job should unschedule itself.
401
+
402
+ ```ruby
403
+ scheduler.cron '5 23 * * *', :last_in => '10d' do
404
+ # ... do something every evening at 23:05 for 10 days
405
+ end
406
+
407
+ scheduler.every '10m', :last_at => Time.now + 10 * 3600 do
408
+ # ... do something every 10 minutes for 10 hours
409
+ end
410
+
411
+ scheduler.every '10m', :last_in => 10 * 3600 do
412
+ # ... do something every 10 minutes for 10 hours
413
+ end
414
+ ```
415
+ :last, :last_at and :last_in all accept a point in time or a duration (number or time string). Use the symbol you think make your schedule more readable.
416
+
417
+ Note: it's OK to change the last_at (nil or a Time instance) directly:
418
+ ```ruby
419
+ job.last_at = nil
420
+ # remove the "last" bound
421
+
422
+ job.last_at = Rufus::Scheduler.parse('2029-12-12')
423
+ # set the last bound
424
+ ```
425
+
426
+ ### :times => nb of times (before auto-unscheduling)
427
+
428
+ One can tell how many times a repeat job (CronJob or EveryJob) is to execute before unscheduling by itself.
429
+
430
+ ```ruby
431
+ scheduler.every '2d', :times => 10 do
432
+ # ... do something every two days, but not more than 10 times
433
+ end
434
+
435
+ scheduler.cron '0 23 * * *', :times => 31 do
436
+ # ... do something every day at 23:00 but do it no more than 31 times
437
+ end
438
+ ```
439
+
440
+ 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.
441
+
442
+ ```ruby
443
+ scheduler.cron '0 23 * * *', :times => nolimit ? nil : 10 do
444
+ # ...
445
+ end
446
+ ```
447
+
448
+ The value set by :times is accessible in the job. It can be modified anytime.
449
+
450
+ ```ruby
451
+ job =
452
+ scheduler.cron '0 23 * * *' do
453
+ # ...
454
+ end
455
+
456
+ # later on...
457
+
458
+ job.times = 10
459
+ # 10 days and it will be over
460
+ ```
461
+
462
+
463
+ ## Job methods
464
+
465
+ When calling a schedule method, the id (String) of the job is returned. Longer schedule methods return Job instances directly. Calling the shorter schedule methods with the :job => true also return Job instances instead of Job ids (Strings).
466
+
467
+ ```ruby
468
+ require 'rufus-scheduler'
469
+
470
+ scheduler = Rufus::Scheduler.new
471
+
472
+ job_id =
473
+ scheduler.in '10d' do
474
+ # ...
475
+ end
476
+
477
+ job =
478
+ scheduler.schedule_in '1w' do
479
+ # ...
480
+ end
481
+
482
+ job =
483
+ scheduler.in '1w', :job => true do
484
+ # ...
485
+ end
486
+ ```
487
+
488
+ Those Job instances have a few interesting methods / properties:
489
+
490
+ ### id, job_id
491
+
492
+ Returns the job id.
493
+
494
+ ```ruby
495
+ job = scheduler.schedule_in('10d') do; end
496
+ job.id
497
+ # => "in_1374072446.8923042_0.0_0"
498
+ ```
499
+
500
+ ### scheduler
501
+
502
+ Returns the scheduler instance itself.
503
+
504
+ ### opts
505
+
506
+ Returns the options passed at the Job creation.
507
+
508
+ ```ruby
509
+ job = scheduler.schedule_in('10d', :tag => 'hello') do; end
510
+ job.opts
511
+ # => { :tag => 'hello' }
512
+ ```
513
+
514
+ ### original
515
+
516
+ Returns the original schedule.
517
+
518
+ ```ruby
519
+ job = scheduler.schedule_in('10d', :tag => 'hello') do; end
520
+ job.original
521
+ # => '10d'
522
+ ```
523
+
524
+ ### callable, handler
525
+
526
+ callable() returns the scheduled block (or the call method of the callable object passed in lieu of a block)
527
+
528
+ handler() returns nil if a block was scheduled and the instance scheduled else.
529
+
530
+ ```ruby
531
+ # when passing a block
532
+
533
+ job =
534
+ scheduler.schedule_in('10d') do
535
+ # ...
536
+ end
537
+
538
+ job.handler
539
+ # => nil
540
+ job.callable
541
+ # => #<Proc:0x00000001dc6f58@/home/jmettraux/whatever.rb:115>
542
+ ```
543
+ and
544
+
545
+ ```ruby
546
+ # when passing something else than a block
547
+
548
+ class MyHandler
549
+ attr_reader :counter
550
+ def initialize
551
+ @counter = 0
552
+ end
553
+ def call(job, time)
554
+ @counter = @counter + 1
555
+ end
556
+ end
557
+
558
+ job = scheduler.schedule_in('10d', MyHandler.new)
559
+
560
+ job.handler
561
+ # => #<Method: MyHandler#call>
562
+ job.callable
563
+ # => #<MyHandler:0x0000000163ae88 @counter=0>
564
+ ```
565
+
566
+
567
+ ### scheduled_at
568
+
569
+ Returns the Time instance when the job got created.
570
+
571
+ ```ruby
572
+ job = scheduler.schedule_in('10d', :tag => 'hello') do; end
573
+ job.scheduled_at
574
+ # => 2013-07-17 23:48:54 +0900
575
+ ```
576
+
577
+ ### last_time
578
+
579
+ Returns the last time the job triggered (is usually nil for AtJob and InJob).
580
+ k
581
+ ```ruby
582
+ job = scheduler.schedule_every('1d') do; end
583
+ # ...
584
+ job.scheduled_at
585
+ # => 2013-07-17 23:48:54 +0900
586
+ ```
587
+
588
+ ### unschedule
589
+
590
+ 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.
591
+
592
+ ### threads
593
+
594
+ Returns the list of threads currently "hosting" runs of this Job instance.
595
+
596
+ ### kill
597
+
598
+ 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).
599
+
600
+ Note: this doesn't unschedule the Job instance.
601
+
602
+ 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.
603
+
604
+ ### running?
605
+
606
+ Returns true if there is at least one running Thread hosting a run of this Job instance.
607
+
608
+ ### scheduled?
609
+
610
+ 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).
611
+
612
+ ### pause, resume, paused?, paused_at
613
+
614
+ These four methods are only available to CronJob, EveryJob and IntervalJob instances. One can pause or resume such a job thanks to them.
615
+
616
+ ```ruby
617
+ job =
618
+ scheduler.schedule_every('10s') do
619
+ # ...
620
+ end
621
+
622
+ job.pause
623
+ # => 2013-07-20 01:22:22 +0900
624
+ job.paused?
625
+ # => true
626
+ job.paused_at
627
+ # => 2013-07-20 01:22:22 +0900
628
+
629
+ job.resume
630
+ # => nil
631
+ ```
632
+
633
+ ### tags
634
+
635
+ Returns the list of tags attached to this Job instance.
636
+
637
+ By default, returns an empty array.
638
+
639
+ ```ruby
640
+ job = scheduler.schedule_in('10d') do; end
641
+ job.tags
642
+ # => []
643
+
644
+ job = scheduler.schedule_in('10d', :tag => 'hello') do; end
645
+ job.tags
646
+ # => [ 'hello' ]
647
+ ```
648
+
649
+ ### []=, [], key? and keys
650
+
651
+ Threads have thread-local variables. Rufus-scheduler jobs have job-local variables.
652
+
653
+ ```ruby
654
+ job =
655
+ @scheduler.schedule_every '1s' do |job|
656
+ job[:timestamp] = Time.now.to_f
657
+ job[:counter] ||= 0
658
+ job[:counter] += 1
659
+ end
660
+
661
+ sleep 3.6
662
+
663
+ job[:counter]
664
+ # => 3
665
+
666
+ job.key?(:timestamp)
667
+ # => true
668
+ job.keys
669
+ # => [ :timestamp, :counter ]
670
+ ```
671
+
672
+ Job-local variables are thread-safe.
673
+
674
+ ## AtJob and InJob methods
675
+
676
+ ### time
677
+
678
+ Returns when the job will trigger (hopefully).
679
+
680
+ ### next_time
681
+
682
+ An alias to time.
683
+
684
+ ## EveryJob, IntervalJob and CronJob methods
685
+
686
+ ### next_time
687
+
688
+ Returns the next time the job will trigger (hopefully).
689
+
690
+ ## EveryJob methods
691
+
692
+ ### frequency
693
+
694
+ It returns the scheduling frequency. For a job scheduled "every 20s", it's 20.
695
+
696
+ It's used to determine if the job frequency is higher than the scheduler frequency (it raises an ArgumentError if that is the case).
697
+
698
+ ## IntervalJob methods
699
+
700
+ ### interval
701
+
702
+ Returns the interval scheduled between each execution of the job.
703
+
704
+ 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.
705
+
706
+ ## CronJob methods
707
+
708
+ ### frequency
709
+
710
+ It returns the shortest interval of time between two potential occurences of the job.
711
+
712
+ For instance:
713
+ ```ruby
714
+ Rufus::Scheduler.parse('* * * * *').frequency # ==> 60
715
+ Rufus::Scheduler.parse('* * * * * *').frequency # ==> 1
716
+
717
+ Rufus::Scheduler.parse('5 23 * * *').frequency # ==> 24 * 3600
718
+ Rufus::Scheduler.parse('5 * * * *').frequency # ==> 3600
719
+ Rufus::Scheduler.parse('10,20,30 * * * *').frequency # ==> 600
720
+ ```
721
+
722
+ It's used to determine if the job frequency is higher than the scheduler frequency (it raises an ArgumentError if that is the case).
723
+
724
+
725
+ ## looking up jobs
726
+
727
+ ### Scheduler#job(job_id)
728
+
729
+ The scheduler #job(job_id) method can be used to lookup Job instances.
730
+
731
+ ```ruby
732
+ require 'rufus-scheduler'
733
+
734
+ scheduler = Rufus::Scheduler.new
735
+
736
+ job_id =
737
+ scheduler.in '10d' do
738
+ # ...
739
+ end
740
+
741
+ # later on...
742
+
743
+ job = scheduler.job(job_id)
744
+ ```
745
+
746
+ ### Scheduler #jobs #at_jobs #in_jobs #every_jobs #interval_jobs and #cron_jobs
747
+
748
+ Are methods for looking up lists of scheduled Job instances.
749
+
750
+ Here is an example:
751
+
752
+ ```ruby
753
+ #
754
+ # let's unschedule all the at jobs
755
+
756
+ scheduler.at_jobs.each(&:unschedule)
757
+ ```
758
+
759
+ ### Scheduler#jobs(:tag / :tags => x)
760
+
761
+ When scheduling a job, one can specify one or more tags attached to the job. These can be used to lookup the job later on.
762
+
763
+ ```ruby
764
+ scheduler.in '10d', :tag => 'main_process' do
765
+ # ...
766
+ end
767
+ scheduler.in '10d', :tags => [ 'main_process', 'side_dish' ] do
768
+ # ...
769
+ end
770
+
771
+ # ...
772
+
773
+ jobs = scheduler.jobs(:tag => 'main_process')
774
+ # find all the jobs with the 'main_process' tag
775
+
776
+ jobs = scheduler.jobs(:tags => [ 'main_process', 'side_dish' ]
777
+ # find all the jobs with the 'main_process' AND 'side_dish' tags
778
+ ```
779
+
780
+ ### Scheduler#running_jobs
781
+
782
+ Returns the list of Job instance that have currently running instances.
783
+
784
+ 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).
785
+
786
+
787
+ ## misc Scheduler methods
788
+
789
+ ### Scheduler#unschedule(job_or_job_id)
790
+
791
+ Unschedule a job given directly or by its id.
792
+
793
+ ### Scheduler#shutdown
794
+
795
+ Shuts down the scheduler, ceases any scheduler/triggering activity.
796
+
797
+ ### Scheduler#shutdown(:wait)
798
+
799
+ Shuts down the scheduler, waits (blocks) until all the jobs cease running.
800
+
801
+ ### Scheduler#shutdown(:kill)
802
+
803
+ Kills all the job (threads) and then shuts the scheduler down. Radical.
804
+
805
+ ### Scheduler#join
806
+
807
+ Let's the current thread join the scheduling thread in rufus-scheduler. The thread comes back when the scheduler gets shut down.
808
+
809
+ ### Scheduler#threads
810
+
811
+ Returns all the threads associated with the scheduler, including the scheduler thread itself.
812
+
813
+ ### Scheduler#work_threads(query=:all/:active/:vacant)
814
+
815
+ Lists the work threads associated with the scheduler. The query option defaults to :all.
816
+
817
+ * :all : all the work threads
818
+ * :active : all the work threads currently running a Job
819
+ * :vacant : all the work threads currently not running a Job
820
+
821
+ Note that the main schedule thread will be returned if it is currently running a Job (ie one of those :blocking => true jobs).
822
+
823
+ ### Scheduler#scheduled?(job_or_job_id)
824
+
825
+ Returns true if the arg is a currently scheduled job (see Job#scheduled?).
826
+
827
+
828
+ ## dealing with job errors
829
+
830
+ 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.
831
+
832
+ ### block jobs
833
+
834
+ As said, jobs could take care of their errors themselves.
835
+
836
+ ```ruby
837
+ scheduler.every '10m' do
838
+ begin
839
+ # do something that might fail...
840
+ rescue => e
841
+ $stderr.puts '-' * 80
842
+ $stderr.puts e.message
843
+ $stderr.puts e.stacktrace
844
+ $stderr.puts '-' * 80
845
+ end
846
+ end
847
+ ```
848
+
849
+ ### callable jobs
850
+
851
+ Jobs are not only shrunk to blocks, here is how the above would look like with a dedicated class.
852
+
853
+ ```ruby
854
+ scheduler.every '10m', Class.new do
855
+ def call(job)
856
+ # do something that might fail...
857
+ rescue => e
858
+ $stderr.puts '-' * 80
859
+ $stderr.puts e.message
860
+ $stderr.puts e.stacktrace
861
+ $stderr.puts '-' * 80
862
+ end
863
+ end
864
+ ```
865
+
866
+ TODO: talk about callable#on_error (if implemented)
867
+
868
+ (see [scheduling handler instances](#scheduling-handler-instances) and [scheduling handler classes](#scheduling-handler-classes) for more about those "callable jobs")
869
+
870
+ ### Rufus::Scheduler#stderr=
871
+
872
+ By default, rufus-scheduler intercepts all errors (that inherit from StandardError) and dumps abundent details to $stderr.
873
+
874
+ If, for example, you'd like to divert that flow to another file (descriptor). You can reassign $stderr for the current Ruby process
875
+
876
+ ```ruby
877
+ $stderr = File.open('/var/log/myapplication.log', 'ab')
878
+ ```
879
+
880
+ or, you can limit that reassignement to the scheduler itself
881
+
882
+ ```ruby
883
+ scheduler.stderr = File.open('/var/log/myapplication.log', 'ab')
884
+ ```
885
+
886
+ ### Rufus::Scheduler#on_error(job, error)
887
+
888
+ 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
889
+
890
+ ```ruby
891
+ def scheduler.on_error(job, error)
892
+
893
+ Logger.warn("intercepted error in #{job.id}: #{error.message}")
894
+ end
895
+ ```
896
+
897
+ ## Rufus::Scheduler #on_pre_trigger and #on_post_trigger callbacks
898
+
899
+ One can bind callbacks before and after jobs trigger:
900
+
901
+ ```ruby
902
+ s = Rufus::Scheduler.new
903
+
904
+ def s.on_pre_trigger(job, trigger_time)
905
+ puts "triggering job #{job.id}..."
906
+ end
907
+
908
+ def s.on_post_trigger(job, trigger_time)
909
+ puts "triggered job #{job.id}."
910
+ end
911
+
912
+ s.every '1s' do
913
+ # ...
914
+ end
915
+ ```
916
+
917
+ The ```trigger_time``` is the time at which the job triggers. It might be a bit before ```Time.now```.
918
+
919
+ Warning: these two callbacks are executed in the scheduler thread, not in the work threads (the threads were the job execution really happens).
920
+
921
+ ### Rufus::Scheduler#on_pre_trigger as a guard
922
+
923
+ Returning ```false``` in on_pre_trigger will prevent the job from triggering. Returning anything else (nil, -1, true, ...) will let the job trigger.
924
+
925
+ 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.
926
+
927
+ ```ruby
928
+ def s.on_pre_trigger(job, trigger_time)
929
+
930
+ return false if Backend.down?
931
+
932
+ puts "triggering job #{job.id}..."
933
+ end
934
+ ```
935
+
936
+ ## Rufus::Scheduler.new options
937
+
938
+ ### :frequency
939
+
940
+ By default, rufus-scheduler sleeps 0.300 second between every step. At each step it checks for jobs to trigger and so on.
941
+
942
+ The :frequency option lets you change that 0.300 second to something else.
943
+
944
+ ```ruby
945
+ scheduler = Rufus::Scheduler.new(:frequency => 5)
946
+ ```
947
+
948
+ It's OK to use a time string to specify the frequency.
949
+
950
+ ```ruby
951
+ scheduler = Rufus::Scheduler.new(:frequency => '2h10m')
952
+ # this scheduler will sleep 2 hours and 10 minutes between every "step"
953
+ ```
954
+
955
+ Use with care.
956
+
957
+ ### :lockfile => "mylockfile.txt"
958
+
959
+ This feature only works on OSes that support the flock (man 2 flock) call.
960
+
961
+ 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.
962
+
963
+ The idea is to guarantee only one scheduler (in a group of scheduler sharing the same lockfile) is running.
964
+
965
+ This is useful in environments where the Ruby process holding the scheduler gets started multiple times.
966
+
967
+ ### :max_work_threads
968
+
969
+ In rufus-scheduler 2.x, by default, each job triggering received its own, new, hthread of execution. In rufus-scheduler 3.x, execution happens in a work thread and the max work thread count defaults to 35.
970
+
971
+ One can set this maximum value when starting the scheduler.
972
+
973
+ ```ruby
974
+ scheduler = Rufus::Scheduler.new(:max_work_threads => 77)
975
+ ```
976
+
977
+ It's OK to increase the :max_work_threads of a running scheduler.
978
+
979
+ ```ruby
980
+ scheduler.max_work_threads += 10
981
+ ```
982
+
983
+
984
+ ## Rufus::Scheduler.singleton
985
+
986
+ Do not want to store a reference to your rufus-scheduler instance?
987
+ Then ```Rufus::Scheduler.singleton``` can help, it returns a singleon instance of the scheduler, initialized the first time this class method is called.
988
+
989
+ ```ruby
990
+ Rufus::Scheduler.singleton.every '10s' { puts "hello, world!" }
991
+ ```
992
+
993
+ 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.
994
+
995
+ ```ruby
996
+ Rufus::Scheduler.singleton(:max_work_threads => 77)
997
+ Rufus::Scheduler.singleton(:max_work_threads => 277) # no effect
998
+ ```
999
+
1000
+ The ```.s``` is a shortcut for ```.singleton```.
1001
+
1002
+ ```ruby
1003
+ Rufus::Scheduler.s.every '10s' { puts "hello, world!" }
1004
+ ```
1005
+
1006
+
1007
+ ## parsing cronlines and time strings
1008
+
1009
+ Rufus::Scheduler provides a class method ```.parse``` to parse time durations and cron strings. It's what it's using when receiving schedules. One can use it diectly (no need to instantiate a Scheduler).
1010
+
1011
+ ```ruby
1012
+ require 'rufus-scheduler'
1013
+
1014
+ Rufus::Scheduler.parse('1w2d')
1015
+ # => 777600.0
1016
+ Rufus::Scheduler.parse('1.0w1.0d')
1017
+ # => 777600.0
1018
+
1019
+ Rufus::Scheduler.parse('Sun Nov 18 16:01:00 2012').strftime('%c')
1020
+ # => 'Sun Nov 18 16:01:00 2012'
1021
+
1022
+ Rufus::Scheduler.parse('Sun Nov 18 16:01:00 2012 Europe/Berlin').strftime('%c %z')
1023
+ # => 'Sun Nov 18 15:01:00 2012 +0000'
1024
+
1025
+ Rufus::Scheduler.parse(0.1)
1026
+ # => 0.1
1027
+
1028
+ Rufus::Scheduler.parse('* * * * *')
1029
+ # => #<Rufus::Scheduler::CronLine:0x00000002be5198
1030
+ # @original="* * * * *", @timezone=nil,
1031
+ # @seconds=[0], @minutes=nil, @hours=nil, @days=nil, @months=nil,
1032
+ # @weekdays=nil, @monthdays=nil>
1033
+ ```
1034
+
1035
+ It returns a number when the output is a duration and a CronLine instance when the input is a cron string.
1036
+
1037
+ It will raise an ArgumentError if it can't parse the input.
1038
+
1039
+ Beyond ```.parse```, there are also ```.parse_cron``` and ```.parse_duration```, for finer granularity.
1040
+
1041
+ There is an interesting helper method named ```.to_duration_hash```:
1042
+
1043
+ ```ruby
1044
+ require 'rufus-scheduler'
1045
+
1046
+ Rufus::Scheduler.to_duration_hash(60)
1047
+ # => { :m => 1 }
1048
+ Rufus::Scheduler.to_duration_hash(62.127)
1049
+ # => { :m => 1, :s => 2, :ms => 127 }
1050
+
1051
+ Rufus::Scheduler.to_duration_hash(62.127, :drop_seconds => true)
1052
+ # => { :m => 1 }
1053
+ ```
1054
+
1055
+
1056
+ ## support
1057
+
1058
+ see [getting help](#getting-help) above.
1059
+
1060
+
1061
+ ## license
1062
+
1063
+ MIT, see [LICENSE.txt](LICENSE.txt)
1064
+