rufus-scheduler 2.0.24 → 3.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (63) hide show
  1. data/CHANGELOG.txt +76 -0
  2. data/CREDITS.txt +23 -0
  3. data/LICENSE.txt +1 -1
  4. data/README.md +1439 -0
  5. data/Rakefile +1 -5
  6. data/TODO.txt +149 -55
  7. data/lib/rufus/{sc → scheduler}/cronline.rb +167 -53
  8. data/lib/rufus/scheduler/job_array.rb +92 -0
  9. data/lib/rufus/scheduler/jobs.rb +633 -0
  10. data/lib/rufus/scheduler/locks.rb +95 -0
  11. data/lib/rufus/scheduler/util.rb +306 -0
  12. data/lib/rufus/scheduler/zones.rb +174 -0
  13. data/lib/rufus/scheduler/zotime.rb +154 -0
  14. data/lib/rufus/scheduler.rb +608 -27
  15. data/rufus-scheduler.gemspec +6 -4
  16. data/spec/basics_spec.rb +54 -0
  17. data/spec/cronline_spec.rb +479 -152
  18. data/spec/error_spec.rb +139 -0
  19. data/spec/job_array_spec.rb +39 -0
  20. data/spec/job_at_spec.rb +58 -0
  21. data/spec/job_cron_spec.rb +128 -0
  22. data/spec/job_every_spec.rb +104 -0
  23. data/spec/job_in_spec.rb +20 -0
  24. data/spec/job_interval_spec.rb +68 -0
  25. data/spec/job_repeat_spec.rb +357 -0
  26. data/spec/job_spec.rb +498 -109
  27. data/spec/lock_custom_spec.rb +47 -0
  28. data/spec/lock_flock_spec.rb +47 -0
  29. data/spec/lock_lockfile_spec.rb +61 -0
  30. data/spec/lock_spec.rb +59 -0
  31. data/spec/parse_spec.rb +263 -0
  32. data/spec/schedule_at_spec.rb +158 -0
  33. data/spec/schedule_cron_spec.rb +66 -0
  34. data/spec/schedule_every_spec.rb +109 -0
  35. data/spec/schedule_in_spec.rb +80 -0
  36. data/spec/schedule_interval_spec.rb +128 -0
  37. data/spec/scheduler_spec.rb +928 -124
  38. data/spec/spec_helper.rb +126 -0
  39. data/spec/threads_spec.rb +96 -0
  40. data/spec/zotime_spec.rb +396 -0
  41. metadata +56 -33
  42. data/README.rdoc +0 -661
  43. data/lib/rufus/otime.rb +0 -3
  44. data/lib/rufus/sc/jobqueues.rb +0 -160
  45. data/lib/rufus/sc/jobs.rb +0 -471
  46. data/lib/rufus/sc/rtime.rb +0 -363
  47. data/lib/rufus/sc/scheduler.rb +0 -636
  48. data/lib/rufus/sc/version.rb +0 -32
  49. data/spec/at_in_spec.rb +0 -47
  50. data/spec/at_spec.rb +0 -125
  51. data/spec/blocking_spec.rb +0 -64
  52. data/spec/cron_spec.rb +0 -134
  53. data/spec/every_spec.rb +0 -304
  54. data/spec/exception_spec.rb +0 -113
  55. data/spec/in_spec.rb +0 -150
  56. data/spec/mutex_spec.rb +0 -159
  57. data/spec/rtime_spec.rb +0 -137
  58. data/spec/schedulable_spec.rb +0 -97
  59. data/spec/spec_base.rb +0 -87
  60. data/spec/stress_schedule_unschedule_spec.rb +0 -159
  61. data/spec/timeout_spec.rb +0 -148
  62. data/test/kjw.rb +0 -113
  63. data/test/t.rb +0 -20
data/README.md ADDED
@@ -0,0 +1,1439 @@
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
+ [![Gem Version](https://badge.fury.io/rb/rufus-scheduler.png)](http://badge.fury.io/rb/rufus-scheduler)
6
+
7
+ Job scheduler for Ruby (at, cron, in and every jobs).
8
+
9
+ **Note**: maybe are you looking for the [README of rufus-scheduler 2.x](https://github.com/jmettraux/rufus-scheduler/blob/two/README.rdoc)?
10
+
11
+ Quickstart:
12
+ ```ruby
13
+ require 'rufus-scheduler'
14
+
15
+ scheduler = Rufus::Scheduler.new
16
+
17
+ scheduler.in '3s' do
18
+ puts 'Hello... Rufus'
19
+ end
20
+
21
+ scheduler.join
22
+ # let the current thread join the scheduler thread
23
+ ```
24
+
25
+ Various forms of scheduling are supported:
26
+ ```ruby
27
+ require 'rufus-scheduler'
28
+
29
+ scheduler = Rufus::Scheduler.new
30
+
31
+ # ...
32
+
33
+ scheduler.in '10d' do
34
+ # do something in 10 days
35
+ end
36
+
37
+ scheduler.at '2030/12/12 23:30:00' do
38
+ # do something at a given point in time
39
+ end
40
+
41
+ scheduler.every '3h' do
42
+ # do something every 3 hours
43
+ end
44
+
45
+ scheduler.cron '5 0 * * *' do
46
+ # do something every day, five minutes after midnight
47
+ # (see "man 5 crontab" in your terminal)
48
+ end
49
+
50
+ # ...
51
+ ```
52
+
53
+ ## non-features
54
+
55
+ Rufus-scheduler (out of the box) is an in-process, in-memory scheduler.
56
+
57
+ It does not persist your schedules. When the process is gone and the scheduler instance with it, the schedules are gone.
58
+
59
+
60
+ ## related and similar gems
61
+
62
+ * [whenever](https://github.com/javan/whenever) - let cron call back your Ruby code, trusted and reliable cron drives your schedule
63
+ * [clockwork](https://github.com/tomykaira/clockwork) - rufus-scheduler inspired gem
64
+ * [crono](https://github.com/plashchynski/crono) - an in-Rails cron scheduler
65
+
66
+ (please note: rufus-scheduler is not a cron replacement)
67
+
68
+
69
+ ## note about the 3.0 line
70
+
71
+ It's a complete rewrite of rufus-scheduler.
72
+
73
+ There is no EventMachine-based scheduler anymore.
74
+
75
+
76
+ ## I don't know what this Ruby thing is, where are my Rails?
77
+
78
+ Sir, I'll drive you right to the [tracks](#so-rails).
79
+
80
+
81
+ ## Notables changes:
82
+
83
+ * As said, no more EventMachine-based scheduler
84
+ * ```scheduler.every('100') {``` will schedule every 100 seconds (previously, it would have been 0.1s). This aligns rufus-scheduler on Ruby's ```sleep(100)```
85
+ * The scheduler isn't catching the whole of Exception anymore, only StandardError
86
+ * 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)
87
+ * Rufus::Scheduler::TimeOutError renamed to Rufus::Scheduler::TimeoutError
88
+ * 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"
89
+ * Introduction of a :lockfile => true/filename mechanism to prevent multiple schedulers from executing
90
+ * "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.
91
+ * Introduction of Scheduler #on_pre_trigger and #on_post_trigger callback points
92
+
93
+
94
+ ## getting help
95
+
96
+ 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.
97
+
98
+ "hello" and "thanks" are not swear words.
99
+
100
+ Go read [how to report bugs effectively](http://www.chiark.greenend.org.uk/~sgtatham/bugs.html), twice.
101
+
102
+ Update: [help_help.md](https://gist.github.com/jmettraux/310fed75f568fd731814) might help help you.
103
+
104
+ ### on StackOverflow
105
+
106
+ Use this [form](http://stackoverflow.com/questions/ask?tags=rufus-scheduler+ruby). It'll create a question flagged "rufus-scheduler" and "ruby".
107
+
108
+ Here are the [questions tagged rufus-scheduler](http://stackoverflow.com/questions/tagged/rufus-scheduler).
109
+
110
+ ### on IRC
111
+
112
+ 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.
113
+
114
+ Please note that I prefer helping over Stack Overflow because it's more searchable than the ruote IRC archive.
115
+
116
+ ### issues
117
+
118
+ 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.
119
+
120
+ ### faq
121
+
122
+ * [It doesn't work...](http://www.chiark.greenend.org.uk/~sgtatham/bugs.html)
123
+ * [I want a refund](http://blog.nodejitsu.com/getting-refunds-on-open-source-projects)
124
+ * [Passenger and rufus-scheduler](http://stackoverflow.com/questions/18108719/debugging-rufus-scheduler/18156180#18156180)
125
+ * [Passenger and rufus-scheduler (2)](http://stackoverflow.com/questions/21861387/rufus-cron-job-not-working-in-apache-passenger#answer-21868555)
126
+ * [Unicorn and rufus-scheduler](https://jkraemer.net/running-rufus-scheduler-in-a-unicorn-rails-app)
127
+
128
+
129
+ ## scheduling
130
+
131
+ Rufus-scheduler supports five kinds of jobs. in, at, every, interval and cron jobs.
132
+
133
+ Most of the rufus-scheduler examples show block scheduling, but it's also OK to schedule handler instances or handler classes.
134
+
135
+ ### in, at, every, interval, cron
136
+
137
+ In and at jobs trigger once.
138
+
139
+ ```ruby
140
+ require 'rufus-scheduler'
141
+
142
+ scheduler = Rufus::Scheduler.new
143
+
144
+ scheduler.in '10d' do
145
+ puts "10 days reminder for review X!"
146
+ end
147
+
148
+ scheduler.at '2014/12/24 2000' do
149
+ puts "merry xmas!"
150
+ end
151
+ ```
152
+
153
+ 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).
154
+
155
+ Every, interval and cron jobs trigger repeatedly.
156
+
157
+ ```ruby
158
+ require 'rufus-scheduler'
159
+
160
+ scheduler = Rufus::Scheduler.new
161
+
162
+ scheduler.every '3h' do
163
+ puts "change the oil filter!"
164
+ end
165
+
166
+ scheduler.interval '2h' do
167
+ puts "thinking..."
168
+ puts sleep(rand * 1000)
169
+ puts "thought."
170
+ end
171
+
172
+ scheduler.cron '00 09 * * *' do
173
+ puts "it's 9am! good morning!"
174
+ end
175
+ ```
176
+
177
+ Every jobs try hard to trigger following the frequency they were scheduled with.
178
+
179
+ 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).
180
+
181
+ 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.
182
+
183
+ ### #schedule_x vs #x
184
+
185
+ schedule_in, schedule_at, schedule_cron, etc will return the new Job instance.
186
+
187
+ in, at, cron will return the new Job instance's id (a String).
188
+
189
+ ```ruby
190
+ job_id =
191
+ scheduler.in '10d' do
192
+ # ...
193
+ end
194
+ job = scheduler.job(job_id)
195
+
196
+ # versus
197
+
198
+ job =
199
+ scheduler.schedule_in '10d' do
200
+ # ...
201
+ end
202
+
203
+ # also
204
+
205
+ job =
206
+ scheduler.in '10d', :job => true do
207
+ # ...
208
+ end
209
+ ```
210
+
211
+ ### #schedule and #repeat
212
+
213
+ Sometimes it pays to be less verbose.
214
+
215
+ The ```#schedule``` methods schedules an at, in or cron job. It just decide based on its input. It returns the Job instance.
216
+
217
+ ```ruby
218
+ scheduler.schedule '10d' do; end.class
219
+ # => Rufus::Scheduler::InJob
220
+
221
+ scheduler.schedule '2013/12/12 12:30' do; end.class
222
+ # => Rufus::Scheduler::AtJob
223
+
224
+ scheduler.schedule '* * * * *' do; end.class
225
+ # => Rufus::Scheduler::CronJob
226
+ ```
227
+
228
+ The ```#repeat``` method schedules and returns an EveryJob or a CronJob.
229
+
230
+ ```ruby
231
+ scheduler.repeat '10d' do; end.class
232
+ # => Rufus::Scheduler::EveryJob
233
+
234
+ scheduler.repeat '* * * * *' do; end.class
235
+ # => Rufus::Scheduler::CronJob
236
+ ```
237
+
238
+ (Yes, no combination heres gives back an IntervalJob).
239
+
240
+ ### schedule blocks arguments (job, time)
241
+
242
+ A schedule block may be given 0, 1 or 2 arguments.
243
+
244
+ 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.
245
+
246
+ ```ruby
247
+ scheduler.every '10m' do |job|
248
+
249
+ status = determine_pie_status
250
+
251
+ if status == 'burnt' || status == 'cooked'
252
+ stop_oven
253
+ takeout_pie
254
+ job.unschedule
255
+ end
256
+ end
257
+ ```
258
+
259
+ The second argument is "time", it's the time when the job got cleared for triggering (not Time.now).
260
+
261
+ Note that time is the time when the job got cleared for triggering. If there are mutexes involved, now = mutex_wait_time + time...
262
+
263
+ #### "every" jobs and changing the next_time in-flight
264
+
265
+ It's OK to change the next_time of an every job in-flight:
266
+
267
+ ```ruby
268
+ scheduler.every '10m' do |job|
269
+
270
+ # ...
271
+
272
+ status = determine_pie_status
273
+
274
+ job.next_time = Time.now + 30 * 60 if status == 'burnt'
275
+ #
276
+ # if burnt, wait 30 minutes for the oven to cool a bit
277
+ end
278
+ ```
279
+
280
+ 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.
281
+
282
+ ### scheduling handler instances
283
+
284
+ It's OK to pass any object, as long as it respond to #call(), when scheduling:
285
+
286
+ ```ruby
287
+ class Handler
288
+ def self.call(job, time)
289
+ p "- Handler called for #{job.id} at #{time}"
290
+ end
291
+ end
292
+
293
+ scheduler.in '10d', Handler
294
+
295
+ # or
296
+
297
+ class OtherHandler
298
+ def initialize(name)
299
+ @name = name
300
+ end
301
+ def call(job, time)
302
+ p "* #{time} - Handler #{name.inspect} called for #{job.id}"
303
+ end
304
+ end
305
+
306
+ oh = OtherHandler.new('Doe')
307
+
308
+ scheduler.every '10m', oh
309
+ scheduler.in '3d5m', oh
310
+ ```
311
+
312
+ The call method must accept 2 (job, time), 1 (job) or 0 arguments.
313
+
314
+ Note that time is the time when the job got cleared for triggering. If there are mutexes involved, now = mutex_wait_time + time...
315
+
316
+ ### scheduling handler classes
317
+
318
+ One can pass a handler class to rufus-scheduler when scheduling. Rufus will instantiate it and that instance will be available via job#handler.
319
+
320
+ ```ruby
321
+ class MyHandler
322
+ attr_reader :count
323
+ def initialize
324
+ @count = 0
325
+ end
326
+ def call(job)
327
+ @count += 1
328
+ puts ". #{self.class} called at #{Time.now} (#{@count})"
329
+ end
330
+ end
331
+
332
+ job = scheduler.schedule_every '35m', MyHandler
333
+
334
+ job.handler
335
+ # => #<MyHandler:0x000000021034f0>
336
+ job.handler.count
337
+ # => 0
338
+ ```
339
+
340
+ If you want to keep that "block feeling":
341
+
342
+ ```ruby
343
+ job_id =
344
+ scheduler.every '10m', Class.new do
345
+ def call(job)
346
+ puts ". hello #{self.inspect} at #{Time.now}"
347
+ end
348
+ end
349
+ ```
350
+
351
+
352
+ ## pause and resume the scheduler
353
+
354
+ The scheduler can be paused via the #pause and #resume methods. One can determine if the scheduler is currently paused by calling #paused?.
355
+
356
+ While paused, the scheduler still accepts schedules, but no schedule will get triggered as long as #resume isn't called.
357
+
358
+
359
+ ## job options
360
+
361
+ ### :blocking => true
362
+
363
+ 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.
364
+
365
+ ### :overlap => false
366
+
367
+ 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.
368
+
369
+ To prevent overlap, one can set :overlap => false. Such a job will not trigger if one of its instance is already running.
370
+
371
+ ### :mutex => mutex_instance / mutex_name / array of mutexes
372
+
373
+ 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).
374
+
375
+ 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.
376
+
377
+ :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.
378
+
379
+ Array of mutexes: original idea and implementation by [Rainux Luo](https://github.com/rainux)
380
+
381
+ 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.
382
+
383
+ ### :timeout => duration or point in time
384
+
385
+ It's OK to specify a timeout when scheduling some work. After the time specified, it gets interrupted via a Rufus::Scheduler::TimeoutError.
386
+
387
+ ```ruby
388
+ scheduler.in '10d', :timeout => '1d' do
389
+ begin
390
+ # ... do something
391
+ rescue Rufus::Scheduler::TimeoutError
392
+ # ... that something got interrupted after 1 day
393
+ end
394
+ end
395
+ ```
396
+
397
+ The :timeout option accepts either a duration (like "1d" or "2w3d") or a point in time (like "2013/12/12 12:00").
398
+
399
+ ### :first_at, :first_in, :first, :first_time
400
+
401
+ This option is for repeat jobs (cron / every) only.
402
+
403
+ It's used to specify the first time after which the repeat job should trigger for the first time.
404
+
405
+ In the case of an "every" job, this will be the first time (modulo the scheduler frequency) the job triggers.
406
+ For a "cron" job, it's the time *after* which the first schedule will trigger.
407
+
408
+ ```ruby
409
+ scheduler.every '2d', :first_at => Time.now + 10 * 3600 do
410
+ # ... every two days, but start in 10 hours
411
+ end
412
+
413
+ scheduler.every '2d', :first_in => '10h' do
414
+ # ... every two days, but start in 10 hours
415
+ end
416
+
417
+ scheduler.cron '00 14 * * *', :first_in => '3d' do
418
+ # ... every day at 14h00, but start after 3 * 24 hours
419
+ end
420
+ ```
421
+
422
+ :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.
423
+
424
+ Note: it's OK to change the first_at (a Time instance) directly:
425
+ ```ruby
426
+ job.first_at = Time.now + 10
427
+ job.first_at = Rufus::Scheduler.parse('2029-12-12')
428
+ ```
429
+
430
+ The first argument (in all its flavours) accepts a :now or :immediately value. That schedules the first occurence for immediate triggering. Consider:
431
+
432
+ ```ruby
433
+ require 'rufus-scheduler'
434
+
435
+ s = Rufus::Scheduler.new
436
+
437
+ n = Time.now; p [ :scheduled_at, n, n.to_f ]
438
+
439
+ s.every '3s', :first => :now do
440
+ n = Time.now; p [ :in, n, n.to_f ]
441
+ end
442
+
443
+ s.join
444
+
445
+ ```
446
+
447
+ that'll output something like:
448
+
449
+ ```
450
+ [:scheduled_at, 2014-01-22 22:21:21 +0900, 1390396881.344438]
451
+ [:in, 2014-01-22 22:21:21 +0900, 1390396881.6453865]
452
+ [:in, 2014-01-22 22:21:24 +0900, 1390396884.648807]
453
+ [:in, 2014-01-22 22:21:27 +0900, 1390396887.651686]
454
+ [:in, 2014-01-22 22:21:30 +0900, 1390396890.6571937]
455
+ ...
456
+ ```
457
+
458
+ ### :last_at, :last_in, :last
459
+
460
+ This option is for repeat jobs (cron / every) only.
461
+
462
+ It indicates the point in time after which the job should unschedule itself.
463
+
464
+ ```ruby
465
+ scheduler.cron '5 23 * * *', :last_in => '10d' do
466
+ # ... do something every evening at 23:05 for 10 days
467
+ end
468
+
469
+ scheduler.every '10m', :last_at => Time.now + 10 * 3600 do
470
+ # ... do something every 10 minutes for 10 hours
471
+ end
472
+
473
+ scheduler.every '10m', :last_in => 10 * 3600 do
474
+ # ... do something every 10 minutes for 10 hours
475
+ end
476
+ ```
477
+ :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.
478
+
479
+ Note: it's OK to change the last_at (nil or a Time instance) directly:
480
+ ```ruby
481
+ job.last_at = nil
482
+ # remove the "last" bound
483
+
484
+ job.last_at = Rufus::Scheduler.parse('2029-12-12')
485
+ # set the last bound
486
+ ```
487
+
488
+ ### :times => nb of times (before auto-unscheduling)
489
+
490
+ One can tell how many times a repeat job (CronJob or EveryJob) is to execute before unscheduling by itself.
491
+
492
+ ```ruby
493
+ scheduler.every '2d', :times => 10 do
494
+ # ... do something every two days, but not more than 10 times
495
+ end
496
+
497
+ scheduler.cron '0 23 * * *', :times => 31 do
498
+ # ... do something every day at 23:00 but do it no more than 31 times
499
+ end
500
+ ```
501
+
502
+ 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.
503
+
504
+ ```ruby
505
+ scheduler.cron '0 23 * * *', :times => nolimit ? nil : 10 do
506
+ # ...
507
+ end
508
+ ```
509
+
510
+ The value set by :times is accessible in the job. It can be modified anytime.
511
+
512
+ ```ruby
513
+ job =
514
+ scheduler.cron '0 23 * * *' do
515
+ # ...
516
+ end
517
+
518
+ # later on...
519
+
520
+ job.times = 10
521
+ # 10 days and it will be over
522
+ ```
523
+
524
+
525
+ ## Job methods
526
+
527
+ 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).
528
+
529
+ ```ruby
530
+ require 'rufus-scheduler'
531
+
532
+ scheduler = Rufus::Scheduler.new
533
+
534
+ job_id =
535
+ scheduler.in '10d' do
536
+ # ...
537
+ end
538
+
539
+ job =
540
+ scheduler.schedule_in '1w' do
541
+ # ...
542
+ end
543
+
544
+ job =
545
+ scheduler.in '1w', :job => true do
546
+ # ...
547
+ end
548
+ ```
549
+
550
+ Those Job instances have a few interesting methods / properties:
551
+
552
+ ### id, job_id
553
+
554
+ Returns the job id.
555
+
556
+ ```ruby
557
+ job = scheduler.schedule_in('10d') do; end
558
+ job.id
559
+ # => "in_1374072446.8923042_0.0_0"
560
+ ```
561
+
562
+ ### scheduler
563
+
564
+ Returns the scheduler instance itself.
565
+
566
+ ### opts
567
+
568
+ Returns the options passed at the Job creation.
569
+
570
+ ```ruby
571
+ job = scheduler.schedule_in('10d', :tag => 'hello') do; end
572
+ job.opts
573
+ # => { :tag => 'hello' }
574
+ ```
575
+
576
+ ### original
577
+
578
+ Returns the original schedule.
579
+
580
+ ```ruby
581
+ job = scheduler.schedule_in('10d', :tag => 'hello') do; end
582
+ job.original
583
+ # => '10d'
584
+ ```
585
+
586
+ ### callable, handler
587
+
588
+ callable() returns the scheduled block (or the call method of the callable object passed in lieu of a block)
589
+
590
+ handler() returns nil if a block was scheduled and the instance scheduled else.
591
+
592
+ ```ruby
593
+ # when passing a block
594
+
595
+ job =
596
+ scheduler.schedule_in('10d') do
597
+ # ...
598
+ end
599
+
600
+ job.handler
601
+ # => nil
602
+ job.callable
603
+ # => #<Proc:0x00000001dc6f58@/home/jmettraux/whatever.rb:115>
604
+ ```
605
+ and
606
+
607
+ ```ruby
608
+ # when passing something else than a block
609
+
610
+ class MyHandler
611
+ attr_reader :counter
612
+ def initialize
613
+ @counter = 0
614
+ end
615
+ def call(job, time)
616
+ @counter = @counter + 1
617
+ end
618
+ end
619
+
620
+ job = scheduler.schedule_in('10d', MyHandler.new)
621
+
622
+ job.handler
623
+ # => #<Method: MyHandler#call>
624
+ job.callable
625
+ # => #<MyHandler:0x0000000163ae88 @counter=0>
626
+ ```
627
+
628
+ ### scheduled_at
629
+
630
+ Returns the Time instance when the job got created.
631
+
632
+ ```ruby
633
+ job = scheduler.schedule_in('10d', :tag => 'hello') do; end
634
+ job.scheduled_at
635
+ # => 2013-07-17 23:48:54 +0900
636
+ ```
637
+
638
+ ### last_time
639
+
640
+ Returns the last time the job triggered (is usually nil for AtJob and InJob).
641
+ k
642
+ ```ruby
643
+ job = scheduler.schedule_every('1d') do; end
644
+ # ...
645
+ job.scheduled_at
646
+ # => 2013-07-17 23:48:54 +0900
647
+ ```
648
+
649
+ ### last_work_time, mean_work_time
650
+
651
+ 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.
652
+
653
+ The attribute `mean_work_time` contains a computed mean work time. It's recomputed after every run (if it's a repeat job).
654
+
655
+ ### unschedule
656
+
657
+ 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.
658
+
659
+ ### threads
660
+
661
+ Returns the list of threads currently "hosting" runs of this Job instance.
662
+
663
+ ### kill
664
+
665
+ 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).
666
+
667
+ Note: this doesn't unschedule the Job instance.
668
+
669
+ 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.
670
+
671
+ ### running?
672
+
673
+ Returns true if there is at least one running Thread hosting a run of this Job instance.
674
+
675
+ ### scheduled?
676
+
677
+ 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).
678
+
679
+ ### pause, resume, paused?, paused_at
680
+
681
+ These four methods are only available to CronJob, EveryJob and IntervalJob instances. One can pause or resume such a job thanks to them.
682
+
683
+ ```ruby
684
+ job =
685
+ scheduler.schedule_every('10s') do
686
+ # ...
687
+ end
688
+
689
+ job.pause
690
+ # => 2013-07-20 01:22:22 +0900
691
+ job.paused?
692
+ # => true
693
+ job.paused_at
694
+ # => 2013-07-20 01:22:22 +0900
695
+
696
+ job.resume
697
+ # => nil
698
+ ```
699
+
700
+ ### tags
701
+
702
+ Returns the list of tags attached to this Job instance.
703
+
704
+ By default, returns an empty array.
705
+
706
+ ```ruby
707
+ job = scheduler.schedule_in('10d') do; end
708
+ job.tags
709
+ # => []
710
+
711
+ job = scheduler.schedule_in('10d', :tag => 'hello') do; end
712
+ job.tags
713
+ # => [ 'hello' ]
714
+ ```
715
+
716
+ ### []=, [], key? and keys
717
+
718
+ Threads have thread-local variables. Rufus-scheduler jobs have job-local variables.
719
+
720
+ ```ruby
721
+ job =
722
+ @scheduler.schedule_every '1s' do |job|
723
+ job[:timestamp] = Time.now.to_f
724
+ job[:counter] ||= 0
725
+ job[:counter] += 1
726
+ end
727
+
728
+ sleep 3.6
729
+
730
+ job[:counter]
731
+ # => 3
732
+
733
+ job.key?(:timestamp)
734
+ # => true
735
+ job.keys
736
+ # => [ :timestamp, :counter ]
737
+ ```
738
+
739
+ Job-local variables are thread-safe.
740
+
741
+ ### call
742
+
743
+ Job instances have a #call method. It simply calls the scheduled block or callable immediately.
744
+
745
+ ```ruby
746
+ job =
747
+ @scheduler.schedule_every '10m' do |job|
748
+ # ...
749
+ end
750
+
751
+ job.call
752
+ ```
753
+
754
+ Warning: the Scheduler#on_error handler is not involved. Error handling is the responsibility of the caller.
755
+
756
+ If the call has to be rescued by the error handler of the scheduler, ```call(true)``` might help:
757
+
758
+ ```ruby
759
+ require 'rufus-scheduler'
760
+
761
+ s = Rufus::Scheduler.new
762
+
763
+ def s.on_error(job, err)
764
+ p [ 'error in scheduled job', job.class, job.original, err.message ]
765
+ rescue
766
+ p $!
767
+ end
768
+
769
+ job =
770
+ s.schedule_in('1d') do
771
+ fail 'again'
772
+ end
773
+
774
+ job.call(true)
775
+ #
776
+ # true lets the error_handler deal with error in the job call
777
+ ```
778
+
779
+ ## AtJob and InJob methods
780
+
781
+ ### time
782
+
783
+ Returns when the job will trigger (hopefully).
784
+
785
+ ### next_time
786
+
787
+ An alias to time.
788
+
789
+ ## EveryJob, IntervalJob and CronJob methods
790
+
791
+ ### next_time
792
+
793
+ Returns the next time the job will trigger (hopefully).
794
+
795
+ ### count
796
+
797
+ Returns how many times the job fired.
798
+
799
+ ## EveryJob methods
800
+
801
+ ### frequency
802
+
803
+ It returns the scheduling frequency. For a job scheduled "every 20s", it's 20.
804
+
805
+ It's used to determine if the job frequency is higher than the scheduler frequency (it raises an ArgumentError if that is the case).
806
+
807
+ ## IntervalJob methods
808
+
809
+ ### interval
810
+
811
+ Returns the interval scheduled between each execution of the job.
812
+
813
+ 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.
814
+
815
+ ## CronJob methods
816
+
817
+ ### frequency
818
+
819
+ It returns the shortest interval of time between two potential occurences of the job.
820
+
821
+ For instance:
822
+ ```ruby
823
+ Rufus::Scheduler.parse('* * * * *').frequency # ==> 60
824
+ Rufus::Scheduler.parse('* * * * * *').frequency # ==> 1
825
+
826
+ Rufus::Scheduler.parse('5 23 * * *').frequency # ==> 24 * 3600
827
+ Rufus::Scheduler.parse('5 * * * *').frequency # ==> 3600
828
+ Rufus::Scheduler.parse('10,20,30 * * * *').frequency # ==> 600
829
+
830
+ Rufus::Scheduler.parse('10,20,30 * * * * *').frequency # ==> 10
831
+ ```
832
+
833
+ It's used to determine if the job frequency is higher than the scheduler frequency (it raises an ArgumentError if that is the case).
834
+
835
+ ### brute_frequency
836
+
837
+ Cron jobs also have a ```#brute_frequency``` method that looks a one year of intervals to determine the shortest delta for the cron. This method can take between 20 to 50 seconds for cron lines that go the second level. ```#frequency``` above, when encountering second level cron lines will take a shortcut to answer as quickly as possible with a usable value.
838
+
839
+
840
+ ## looking up jobs
841
+
842
+ ### Scheduler#job(job_id)
843
+
844
+ The scheduler ```#job(job_id)``` method can be used to lookup Job instances.
845
+
846
+ ```ruby
847
+ require 'rufus-scheduler'
848
+
849
+ scheduler = Rufus::Scheduler.new
850
+
851
+ job_id =
852
+ scheduler.in '10d' do
853
+ # ...
854
+ end
855
+
856
+ # later on...
857
+
858
+ job = scheduler.job(job_id)
859
+ ```
860
+
861
+ ### Scheduler #jobs #at_jobs #in_jobs #every_jobs #interval_jobs and #cron_jobs
862
+
863
+ Are methods for looking up lists of scheduled Job instances.
864
+
865
+ Here is an example:
866
+
867
+ ```ruby
868
+ #
869
+ # let's unschedule all the at jobs
870
+
871
+ scheduler.at_jobs.each(&:unschedule)
872
+ ```
873
+
874
+ ### Scheduler#jobs(:tag / :tags => x)
875
+
876
+ 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.
877
+
878
+ ```ruby
879
+ scheduler.in '10d', :tag => 'main_process' do
880
+ # ...
881
+ end
882
+ scheduler.in '10d', :tags => [ 'main_process', 'side_dish' ] do
883
+ # ...
884
+ end
885
+
886
+ # ...
887
+
888
+ jobs = scheduler.jobs(:tag => 'main_process')
889
+ # find all the jobs with the 'main_process' tag
890
+
891
+ jobs = scheduler.jobs(:tags => [ 'main_process', 'side_dish' ]
892
+ # find all the jobs with the 'main_process' AND 'side_dish' tags
893
+ ```
894
+
895
+ ### Scheduler#running_jobs
896
+
897
+ Returns the list of Job instance that have currently running instances.
898
+
899
+ 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).
900
+
901
+
902
+ ## misc Scheduler methods
903
+
904
+ ### Scheduler#unschedule(job_or_job_id)
905
+
906
+ Unschedule a job given directly or by its id.
907
+
908
+ ### Scheduler#shutdown
909
+
910
+ Shuts down the scheduler, ceases any scheduler/triggering activity.
911
+
912
+ ### Scheduler#shutdown(:wait)
913
+
914
+ Shuts down the scheduler, waits (blocks) until all the jobs cease running.
915
+
916
+ ### Scheduler#shutdown(:kill)
917
+
918
+ Kills all the job (threads) and then shuts the scheduler down. Radical.
919
+
920
+ ### Scheduler#down?
921
+
922
+ Returns true if the scheduler has been shut down.
923
+
924
+ ### Scheduler#started_at
925
+
926
+ Returns the Time instance at which the scheduler got started.
927
+
928
+ ### Scheduler #uptime / #uptime_s
929
+
930
+ Returns since the count of seconds for which the scheduler has been running.
931
+
932
+ ```#uptime_s``` returns this count in a String easier to grasp for humans, like ```"3d12m45s123"```.
933
+
934
+ ### Scheduler#join
935
+
936
+ Let's the current thread join the scheduling thread in rufus-scheduler. The thread comes back when the scheduler gets shut down.
937
+
938
+ ### Scheduler#threads
939
+
940
+ Returns all the threads associated with the scheduler, including the scheduler thread itself.
941
+
942
+ ### Scheduler#work_threads(query=:all/:active/:vacant)
943
+
944
+ Lists the work threads associated with the scheduler. The query option defaults to :all.
945
+
946
+ * :all : all the work threads
947
+ * :active : all the work threads currently running a Job
948
+ * :vacant : all the work threads currently not running a Job
949
+
950
+ Note that the main schedule thread will be returned if it is currently running a Job (ie one of those :blocking => true jobs).
951
+
952
+ ### Scheduler#scheduled?(job_or_job_id)
953
+
954
+ Returns true if the arg is a currently scheduled job (see Job#scheduled?).
955
+
956
+ ### Scheduler#occurrences(time0, time1)
957
+
958
+ Returns a hash ```{ job => [ t0, t1, ... ] }``` mapping jobs to their potential trigger time within the ```[ time0, time1 ]``` span.
959
+
960
+ Please note that, for interval jobs, the ```#mean_work_time``` is used, so the result is only a prediction.
961
+
962
+ ### Scheduler#timeline(time0, time1)
963
+
964
+ Like `#occurrences` but returns a list ```[ [ t0, job0 ], [ t1, job1 ], ... ]``` of time + job pairs.
965
+
966
+
967
+ ## dealing with job errors
968
+
969
+ 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.
970
+
971
+ ### block jobs
972
+
973
+ As said, jobs could take care of their errors themselves.
974
+
975
+ ```ruby
976
+ scheduler.every '10m' do
977
+ begin
978
+ # do something that might fail...
979
+ rescue => e
980
+ $stderr.puts '-' * 80
981
+ $stderr.puts e.message
982
+ $stderr.puts e.stacktrace
983
+ $stderr.puts '-' * 80
984
+ end
985
+ end
986
+ ```
987
+
988
+ ### callable jobs
989
+
990
+ Jobs are not only shrunk to blocks, here is how the above would look like with a dedicated class.
991
+
992
+ ```ruby
993
+ scheduler.every '10m', Class.new do
994
+ def call(job)
995
+ # do something that might fail...
996
+ rescue => e
997
+ $stderr.puts '-' * 80
998
+ $stderr.puts e.message
999
+ $stderr.puts e.stacktrace
1000
+ $stderr.puts '-' * 80
1001
+ end
1002
+ end
1003
+ ```
1004
+
1005
+ TODO: talk about callable#on_error (if implemented)
1006
+
1007
+ (see [scheduling handler instances](#scheduling-handler-instances) and [scheduling handler classes](#scheduling-handler-classes) for more about those "callable jobs")
1008
+
1009
+ ### Rufus::Scheduler#stderr=
1010
+
1011
+ By default, rufus-scheduler intercepts all errors (that inherit from StandardError) and dumps abundent details to $stderr.
1012
+
1013
+ If, for example, you'd like to divert that flow to another file (descriptor). You can reassign $stderr for the current Ruby process
1014
+
1015
+ ```ruby
1016
+ $stderr = File.open('/var/log/myapplication.log', 'ab')
1017
+ ```
1018
+
1019
+ or, you can limit that reassignement to the scheduler itself
1020
+
1021
+ ```ruby
1022
+ scheduler.stderr = File.open('/var/log/myapplication.log', 'ab')
1023
+ ```
1024
+
1025
+ ### Rufus::Scheduler#on_error(job, error)
1026
+
1027
+ 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
1028
+
1029
+ ```ruby
1030
+ def scheduler.on_error(job, error)
1031
+
1032
+ Logger.warn("intercepted error in #{job.id}: #{error.message}")
1033
+ end
1034
+ ```
1035
+
1036
+ ## Rufus::Scheduler #on_pre_trigger and #on_post_trigger callbacks
1037
+
1038
+ One can bind callbacks before and after jobs trigger:
1039
+
1040
+ ```ruby
1041
+ s = Rufus::Scheduler.new
1042
+
1043
+ def s.on_pre_trigger(job, trigger_time)
1044
+ puts "triggering job #{job.id}..."
1045
+ end
1046
+
1047
+ def s.on_post_trigger(job, trigger_time)
1048
+ puts "triggered job #{job.id}."
1049
+ end
1050
+
1051
+ s.every '1s' do
1052
+ # ...
1053
+ end
1054
+ ```
1055
+
1056
+ The ```trigger_time``` is the time at which the job triggers. It might be a bit before ```Time.now```.
1057
+
1058
+ Warning: these two callbacks are executed in the scheduler thread, not in the work threads (the threads were the job execution really happens).
1059
+
1060
+ ### Rufus::Scheduler#on_pre_trigger as a guard
1061
+
1062
+ Returning ```false``` in on_pre_trigger will prevent the job from triggering. Returning anything else (nil, -1, true, ...) will let the job trigger.
1063
+
1064
+ 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.
1065
+
1066
+ ```ruby
1067
+ def s.on_pre_trigger(job, trigger_time)
1068
+
1069
+ return false if Backend.down?
1070
+
1071
+ puts "triggering job #{job.id}..."
1072
+ end
1073
+ ```
1074
+
1075
+ ## Rufus::Scheduler.new options
1076
+
1077
+ ### :frequency
1078
+
1079
+ By default, rufus-scheduler sleeps 0.300 second between every step. At each step it checks for jobs to trigger and so on.
1080
+
1081
+ The :frequency option lets you change that 0.300 second to something else.
1082
+
1083
+ ```ruby
1084
+ scheduler = Rufus::Scheduler.new(:frequency => 5)
1085
+ ```
1086
+
1087
+ It's OK to use a time string to specify the frequency.
1088
+
1089
+ ```ruby
1090
+ scheduler = Rufus::Scheduler.new(:frequency => '2h10m')
1091
+ # this scheduler will sleep 2 hours and 10 minutes between every "step"
1092
+ ```
1093
+
1094
+ Use with care.
1095
+
1096
+ ### :lockfile => "mylockfile.txt"
1097
+
1098
+ This feature only works on OSes that support the flock (man 2 flock) call.
1099
+
1100
+ 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.
1101
+
1102
+ The idea is to guarantee only one scheduler (in a group of scheduler sharing the same lockfile) is running.
1103
+
1104
+ This is useful in environments where the Ruby process holding the scheduler gets started multiple times.
1105
+
1106
+ 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.
1107
+
1108
+ ### :scheduler_lock
1109
+
1110
+ (since rufus-scheduler 3.0.9)
1111
+
1112
+ 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.
1113
+
1114
+ Here is a sample of a scheduler lock that only lets the scheduler on host "coffee.example.com" start:
1115
+ ```ruby
1116
+ class HostLock
1117
+ def initialize(lock_name)
1118
+ @lock_name = lock_name
1119
+ end
1120
+ def lock
1121
+ @lock_name == `hostname -f`.strip
1122
+ end
1123
+ def unlock
1124
+ true
1125
+ end
1126
+ end
1127
+
1128
+ scheduler =
1129
+ Rufus::Scheduler.new(:scheduler_lock => HostLock.new('coffee.example.com'))
1130
+ ```
1131
+
1132
+ By default, the scheduler_lock is an instance of `Rufus::Scheduler::NullLock`, with a `#lock` that returns true.
1133
+
1134
+ ### :trigger_lock
1135
+
1136
+ (since rufus-scheduler 3.0.9)
1137
+
1138
+ 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).
1139
+
1140
+ 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...
1141
+ ```ruby
1142
+ class PingLock
1143
+ def initialize(other_host)
1144
+ @other_host = other_host
1145
+ end
1146
+ def lock
1147
+ ! system("ping -c 1 #{@other_host}")
1148
+ end
1149
+ end
1150
+
1151
+ scheduler =
1152
+ Rufus::Scheduler.new(:trigger_lock => PingLock.new('main.example.com'))
1153
+ ```
1154
+
1155
+ By default, the trigger_lock is an instance of `Rufus::Scheduler::NullLock`, with a `#lock` that always returns true.
1156
+
1157
+ 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).
1158
+
1159
+ ### :max_work_threads
1160
+
1161
+ 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.
1162
+
1163
+ One can set this maximum value when starting the scheduler.
1164
+
1165
+ ```ruby
1166
+ scheduler = Rufus::Scheduler.new(:max_work_threads => 77)
1167
+ ```
1168
+
1169
+ It's OK to increase the :max_work_threads of a running scheduler.
1170
+
1171
+ ```ruby
1172
+ scheduler.max_work_threads += 10
1173
+ ```
1174
+
1175
+
1176
+ ## Rufus::Scheduler.singleton
1177
+
1178
+ Do not want to store a reference to your rufus-scheduler instance?
1179
+ Then ```Rufus::Scheduler.singleton``` can help, it returns a singleon instance of the scheduler, initialized the first time this class method is called.
1180
+
1181
+ ```ruby
1182
+ Rufus::Scheduler.singleton.every '10s' { puts "hello, world!" }
1183
+ ```
1184
+
1185
+ 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.
1186
+
1187
+ ```ruby
1188
+ Rufus::Scheduler.singleton(:max_work_threads => 77)
1189
+ Rufus::Scheduler.singleton(:max_work_threads => 277) # no effect
1190
+ ```
1191
+
1192
+ The ```.s``` is a shortcut for ```.singleton```.
1193
+
1194
+ ```ruby
1195
+ Rufus::Scheduler.s.every '10s' { puts "hello, world!" }
1196
+ ```
1197
+
1198
+
1199
+ ## advanced lock schemes
1200
+
1201
+ As seen above, rufus-scheduler proposes the [:lockfile](#lockfile--mylockfiletxt) system out of the box. If in a group of schedulers only one is supposed to run, the lockfile mecha prevents schedulers that have not set/created the lockfile from running.
1202
+
1203
+ There are situation where this is not sufficient.
1204
+
1205
+ By overriding #lock and #unlock, one can customize how his schedulers lock.
1206
+
1207
+ This example was provided by [Eric Lindvall](https://github.com/eric):
1208
+
1209
+ ```ruby
1210
+ class ZookeptScheduler < Rufus::Scheduler
1211
+
1212
+ def initialize(zookeeper, opts={})
1213
+ @zk = zookeeper
1214
+ super(opts)
1215
+ end
1216
+
1217
+ def lock
1218
+ @zk_locker = @zk.exclusive_locker('scheduler')
1219
+ @zk_locker.lock # returns true if the lock was acquired, false else
1220
+ end
1221
+
1222
+ def unlock
1223
+ @zk_locker.unlock
1224
+ end
1225
+
1226
+ def confirm_lock
1227
+ return false if down?
1228
+ @zk_locker.assert!
1229
+ rescue ZK::Exceptions::LockAssertionFailedError => e
1230
+ # we've lost the lock, shutdown (and return false to at least prevent
1231
+ # this job from triggering
1232
+ shutdown
1233
+ false
1234
+ end
1235
+ end
1236
+ ```
1237
+
1238
+ This uses a [zookeeper](http://zookeeper.apache.org/) to make sure only one scheduler in a group of distributed schedulers runs.
1239
+
1240
+ The methods #lock and #unlock are overriden and #confirm_lock is provided,
1241
+ to make sure that the lock is still valid.
1242
+
1243
+ 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.
1244
+
1245
+ ### :scheduler_lock and :trigger_lock
1246
+
1247
+ (introduced in rufus-scheduler 3.0.9).
1248
+
1249
+ Another way of prodiving `#lock`, `#unlock` and `#confirm_lock` to a rufus-scheduler is by using the `:scheduler_lock` and `:trigger_lock` options.
1250
+
1251
+ See [:trigger_lock](#trigger_lock) and [:scheduler_lock](#scheduler_lock).
1252
+
1253
+ 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).
1254
+
1255
+ One has to be careful with what goes in `#confirm_lock` or in a trigger lock, as it gets called before each trigger.
1256
+
1257
+ 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.
1258
+
1259
+
1260
+ ## parsing cronlines and time strings
1261
+
1262
+ 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).
1263
+
1264
+ ```ruby
1265
+ require 'rufus-scheduler'
1266
+
1267
+ Rufus::Scheduler.parse('1w2d')
1268
+ # => 777600.0
1269
+ Rufus::Scheduler.parse('1.0w1.0d')
1270
+ # => 777600.0
1271
+
1272
+ Rufus::Scheduler.parse('Sun Nov 18 16:01:00 2012').strftime('%c')
1273
+ # => 'Sun Nov 18 16:01:00 2012'
1274
+
1275
+ Rufus::Scheduler.parse('Sun Nov 18 16:01:00 2012 Europe/Berlin').strftime('%c %z')
1276
+ # => 'Sun Nov 18 15:01:00 2012 +0000'
1277
+
1278
+ Rufus::Scheduler.parse(0.1)
1279
+ # => 0.1
1280
+
1281
+ Rufus::Scheduler.parse('* * * * *')
1282
+ # => #<Rufus::Scheduler::CronLine:0x00000002be5198
1283
+ # @original="* * * * *", @timezone=nil,
1284
+ # @seconds=[0], @minutes=nil, @hours=nil, @days=nil, @months=nil,
1285
+ # @weekdays=nil, @monthdays=nil>
1286
+ ```
1287
+
1288
+ It returns a number when the output is a duration and a CronLine instance when the input is a cron string.
1289
+
1290
+ It will raise an ArgumentError if it can't parse the input.
1291
+
1292
+ Beyond ```.parse```, there are also ```.parse_cron``` and ```.parse_duration```, for finer granularity.
1293
+
1294
+ There is an interesting helper method named ```.to_duration_hash```:
1295
+
1296
+ ```ruby
1297
+ require 'rufus-scheduler'
1298
+
1299
+ Rufus::Scheduler.to_duration_hash(60)
1300
+ # => { :m => 1 }
1301
+ Rufus::Scheduler.to_duration_hash(62.127)
1302
+ # => { :m => 1, :s => 2, :ms => 127 }
1303
+
1304
+ Rufus::Scheduler.to_duration_hash(62.127, :drop_seconds => true)
1305
+ # => { :m => 1 }
1306
+ ```
1307
+
1308
+ ### cronline notations specific to rufus-scheduler
1309
+
1310
+ #### first Monday, last Sunday et al
1311
+
1312
+ To schedule something at noon every first Monday of the month:
1313
+
1314
+ ```ruby
1315
+ scheduler.cron('00 12 * * mon#1') do
1316
+ # ...
1317
+ end
1318
+ ```
1319
+
1320
+ To schedule something at noon the last Sunday of every month:
1321
+
1322
+ ```ruby
1323
+ scheduler.cron('00 12 * * sun#-1') do
1324
+ # ...
1325
+ end
1326
+ #
1327
+ # OR
1328
+ #
1329
+ scheduler.cron('00 12 * * sun#L') do
1330
+ # ...
1331
+ end
1332
+ ```
1333
+
1334
+ Such cronlines can be tested with scripts like:
1335
+
1336
+ ```ruby
1337
+ require 'rufus-scheduler'
1338
+
1339
+ Time.now
1340
+ # => 2013-10-26 07:07:08 +0900
1341
+ Rufus::Scheduler.parse('* * * * mon#1').next_time
1342
+ # => 2013-11-04 00:00:00 +0900
1343
+ ```
1344
+
1345
+ #### L (last day of month)
1346
+
1347
+ L can be used in the "day" slot:
1348
+
1349
+ In this example, the cronline is supposed to trigger every last day of the month at noon:
1350
+
1351
+ ```ruby
1352
+ require 'rufus-scheduler'
1353
+ Time.now
1354
+ # => 2013-10-26 07:22:09 +0900
1355
+ Rufus::Scheduler.parse('00 12 L * *').next_time
1356
+ # => 2013-10-31 12:00:00 +0900
1357
+ ```
1358
+
1359
+
1360
+ ## a note about timezones
1361
+
1362
+ Cron schedules and at schedules support the specification of a timezone.
1363
+
1364
+ ```ruby
1365
+ scheduler.cron '0 22 * * 1-5 America/Chicago' do
1366
+ # the job...
1367
+ end
1368
+
1369
+ scheduler.at '2013-12-12 14:00 Pacific/Samoa' do
1370
+ puts "it's tea time!"
1371
+ end
1372
+
1373
+ # or even
1374
+
1375
+ Rufus::Scheduler.parse("2013-12-12 14:00 Pacific/Saipan")
1376
+ # => 2013-12-12 04:00:00 UTC
1377
+ ```
1378
+
1379
+
1380
+ ## so Rails?
1381
+
1382
+ 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...
1383
+
1384
+ Here is an example initializer:
1385
+
1386
+ ```ruby
1387
+ #
1388
+ # config/initializers/scheduler.rb
1389
+
1390
+ require 'rufus-scheduler'
1391
+
1392
+ # Let's use the rufus-scheduler singleton
1393
+ #
1394
+ s = Rufus::Scheduler.singleton
1395
+
1396
+
1397
+ # Stupid recurrent task...
1398
+ #
1399
+ s.every '1m' do
1400
+
1401
+ Rails.logger.info "hello, it's #{Time.now}"
1402
+ end
1403
+ ```
1404
+
1405
+ And now you tell me that this is good, but you want to schedule stuff from your controller.
1406
+
1407
+ Maybe:
1408
+
1409
+ ```ruby
1410
+ class ScheController < ApplicationController
1411
+
1412
+ # GET /sche/
1413
+ #
1414
+ def index
1415
+
1416
+ job_id =
1417
+ Rufus::Scheduler.singleton.in '5s' do
1418
+ Rails.logger.info "time flies, it's now #{Time.now}"
1419
+ end
1420
+
1421
+ render :text => "scheduled job #{job_id}"
1422
+ end
1423
+ end
1424
+ ```
1425
+
1426
+ The rufus-scheduler singleton is instantiated in the ```config/initializers/scheduler.rb``` file, it's then available throughout the webapp via ```Rufus::Scheduler.singleton```.
1427
+
1428
+ *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.
1429
+
1430
+
1431
+ ## support
1432
+
1433
+ see [getting help](#getting-help) above.
1434
+
1435
+
1436
+ ## license
1437
+
1438
+ MIT, see [LICENSE.txt](LICENSE.txt)
1439
+