Class: Fugit::Cron

Inherits:
Object
  • Object
show all
Defined in:
lib/fugit/cron.rb

Defined Under Namespace

Modules: Parser Classes: CronIterator, Frequency, TimeCursor

Constant Summary collapse

SPECIALS =
{
'@reboot' => :reboot,
'@yearly' => '0 0 1 1 *',
'@annually' => '0 0 1 1 *',
'@monthly' => '0 0 1 * *',
'@weekly' => '0 0 * * 0',
'@daily' => '0 0 * * *',
'@midnight' => '0 0 * * *',
'@noon' => '0 12 * * *',
'@hourly' => '0 * * * *' }.freeze
MAXDAYS =
[
nil, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ].freeze
MAX_ITERATION_COUNT =
2048
SLOTS =
[
[ :seconds, 1, 60 ],
[ :minutes, 60, 60 ],
[ :hours, 3600, 24 ],
[ :days, DAY_S, 365 ] ].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#hoursObject (readonly)

Returns the value of attribute hours.



22
23
24
# File 'lib/fugit/cron.rb', line 22

def hours
  @hours
end

#minutesObject (readonly)

Returns the value of attribute minutes.



22
23
24
# File 'lib/fugit/cron.rb', line 22

def minutes
  @minutes
end

#monthdaysObject (readonly)

Returns the value of attribute monthdays.



22
23
24
# File 'lib/fugit/cron.rb', line 22

def monthdays
  @monthdays
end

#monthsObject (readonly)

Returns the value of attribute months.



22
23
24
# File 'lib/fugit/cron.rb', line 22

def months
  @months
end

#originalObject (readonly)

Returns the value of attribute original.



20
21
22
# File 'lib/fugit/cron.rb', line 20

def original
  @original
end

#secondsObject (readonly)

Returns the value of attribute seconds.



22
23
24
# File 'lib/fugit/cron.rb', line 22

def seconds
  @seconds
end

#timezoneObject (readonly)

Returns the value of attribute timezone.



22
23
24
# File 'lib/fugit/cron.rb', line 22

def timezone
  @timezone
end

#weekdaysObject (readonly)

Returns the value of attribute weekdays.



22
23
24
# File 'lib/fugit/cron.rb', line 22

def weekdays
  @weekdays
end

#zoneObject (readonly)

Returns the value of attribute zone.



20
21
22
# File 'lib/fugit/cron.rb', line 20

def zone
  @zone
end

Class Method Details

.do_parse(s) ⇒ Object



54
55
56
57
58
# File 'lib/fugit/cron.rb', line 54

def do_parse(s)

  parse(s) ||
  fail(ArgumentError.new("invalid cron string #{trunc(s)}"))
end

.new(original) ⇒ Object



27
28
29
30
# File 'lib/fugit/cron.rb', line 27

def new(original)

  parse(original)
end

.parse(s) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/fugit/cron.rb', line 32

def parse(s)

  return s if s.is_a?(self)
  return nil unless s.is_a?(String)

  s0 = s
  s = s.strip

  s =
    if s[0, 1] == '@'
      ss = s.split(/\s+/, 2)
      [ SPECIALS[ss[0]] || ss, *ss[1..-1] ].join(' ')
    else
      s
    end

#p s; Raabro.pp(Parser.parse(s, debug: 3), colors: true)
  h = Parser.parse(s)

  self.allocate.send(:init, s0, h)
end

Instance Method Details

#==(o) ⇒ Object Also known as: eql?



506
507
508
509
# File 'lib/fugit/cron.rb', line 506

def ==(o)

  o.is_a?(::Fugit::Cron) && o.to_a == to_a
end

#brute_frequency(year = 2017) ⇒ Object

Mostly used as a #next_time sanity check. Avoid for “business” use, it’s slow.

2017 is a non leap year (though it is preceded by a leap second on 2016-12-31)

Nota bene: cron with seconds are not supported.



404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/fugit/cron.rb', line 404

def brute_frequency(year=2017)

  FREQUENCY_CACHE["#{to_cron_s}|#{year}"] ||=
    begin

      deltas = []

      t = EtOrbi.make_time("#{year}-01-01") - 1
      t0 = nil
      t1 = nil

      loop do
        t1 = next_time(t)
        deltas << (t1 - t).to_i if t0
        t0 ||= t1
        break if deltas.any? && t1.year > year
        break if t1.year - t0.year > 7
        t = t1
      end

      Frequency.new(deltas, t1 - t0)
    end
end

#day_match?(nt) ⇒ Boolean



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/fugit/cron.rb', line 215

def day_match?(nt)

  if @weekdays && @monthdays

    return weekday_match?(nt) && monthday_match?(nt) \
      if @day_and
        #
        # extension for fugit, gh-78

    return weekday_match?(nt) || monthday_match?(nt)
      #
      # From `man 5 crontab`
      #
      # Note: The day of a command's execution can be specified
      # by two fields -- day of month, and day of week.
      # If both fields are restricted (ie, are not *), the command will be
      # run when either field matches the current time.
      # For example, ``30 4 1,15 * 5'' would cause a command to be run
      # at 4:30 am on the 1st and 15th of each month, plus every Friday.
      #
      # as seen in gh-5 and gh-35
  end


  return false unless weekday_match?(nt)
  return false unless monthday_match?(nt)

  true
end

#hashObject



512
513
514
515
# File 'lib/fugit/cron.rb', line 512

def hash

  to_a.hash
end

#hour_match?(nt) ⇒ Boolean



172
# File 'lib/fugit/cron.rb', line 172

def hour_match?(nt); ( ! @hours) || @hours.include?(nt.hour); end

#match?(t) ⇒ Boolean



245
246
247
248
249
250
251
# File 'lib/fugit/cron.rb', line 245

def match?(t)

  t = Fugit.do_parse_at(t).translate(@timezone)

  month_match?(t) && day_match?(t) &&
  hour_match?(t) && min_match?(t) && sec_match?(t)
end

#min_match?(nt) ⇒ Boolean



173
# File 'lib/fugit/cron.rb', line 173

def min_match?(nt); ( ! @minutes) || @minutes.include?(nt.min); end

#month_match?(nt) ⇒ Boolean



171
# File 'lib/fugit/cron.rb', line 171

def month_match?(nt); ( ! @months) || @months.include?(nt.month); end

#monthday_match?(nt) ⇒ Boolean



204
205
206
207
208
209
210
211
212
213
# File 'lib/fugit/cron.rb', line 204

def monthday_match?(nt)

  return true if @monthdays.nil?

  last = (TimeCursor.new(self, nt).inc_month.time - 24 * 3600).day + 1

  @monthdays
    .collect { |d| d < 1 ? last + d : d }
    .include?(nt.day)
end

#next(from = ::EtOrbi::EoTime.now) ⇒ Object

Returns an ::Enumerable instance that yields each “next time” in succession



369
370
371
372
# File 'lib/fugit/cron.rb', line 369

def next(from=::EtOrbi::EoTime.now)

  CronIterator.new(self, :next_time, from)
end

#next_time(from = ::EtOrbi::EoTime.now) ⇒ Object

See gh-15 and tst/iteration_count.rb

Initially set to 1024 after seeing the worst case for #next_time at 167 iterations, I placed it at 2048 after experimenting with gh-18 and noticing some > 1024 for some experiments. 2048 should be ok.



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/fugit/cron.rb', line 262

def next_time(from=::EtOrbi::EoTime.now)

  from = ::EtOrbi.make_time(from)
  sfrom = from.strftime('%F|%T')
  ifrom = from.to_i

  i = 0
  t = TimeCursor.new(self, from.translate(@timezone))
    #
    # the translation occurs in the timezone of
    # this Fugit::Cron instance

  zfrom = t.time.strftime('%z|%Z')

  loop do

    fail RuntimeError.new(
      "too many loops for #{@original.inspect} #next_time, breaking, " +
      "cron expression most likely invalid (Feb 30th like?), " +
      "please fill an issue at https://git.io/fjJC9"
    ) if (i += 1) > MAX_ITERATION_COUNT

#tt = t.time;
#puts "  #{tt.strftime('%F %T %:z %A')} #{tt.rweek} #{tt.rweek % 2}"
    (ifrom == t.to_i) && (t.inc(1); next)
    month_match?(t) || (t.inc_month; next)
    day_match?(t) || (t.inc_day; next)
    hour_match?(t) || (t.inc_hour; next)
    min_match?(t) || (t.inc_min; next)
    sec_match?(t) || (t.inc_sec; next)

    tt = t.time
    st = tt.strftime('%F|%T')
    zt = tt.strftime('%z|%Z')
      #
    if st == sfrom && zt != zfrom
      from, sfrom, zfrom, ifrom = tt, st, zt, t.to_i
      next
    end
      #
      # when transitioning out of DST, this prevents #next_time from
      # yielding the same literal time twice in a row, see gh-6

    break
  end

  t.time.translate(from.zone)
    #
    # the answer time is in the same timezone as the `from`
    # starting point
end

#prev(from = ::EtOrbi::EoTime.now) ⇒ Object

Returns an ::Enumerable instance that yields each “previous time” in succession



377
378
379
380
# File 'lib/fugit/cron.rb', line 377

def prev(from=::EtOrbi::EoTime.now)

  CronIterator.new(self, :previous_time, from)
end

#previous_time(from = ::EtOrbi::EoTime.now) ⇒ Object



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/fugit/cron.rb', line 314

def previous_time(from=::EtOrbi::EoTime.now)

  from = ::EtOrbi.make_time(from)

  i = 0
  t = TimeCursor.new(self, (from - 1).translate(@timezone))

  loop do

    fail RuntimeError.new(
      "too many loops for #{@original.inspect} #previous_time, breaking, " +
      "cron expression most likely invalid (Feb 30th like?), " +
      "please fill an issue at https://git.io/fjJCQ"
    ) if (i += 1) > MAX_ITERATION_COUNT

#tt = t.time;
#puts "  #{tt.strftime('%F %T %:z %A')} #{tt.rweek} #{tt.rweek % 4}"
    month_match?(t) || (t.dec_month; next)
    day_match?(t) || (t.dec_day; next)
    hour_match?(t) || (t.dec_hour; next)
    min_match?(t) || (t.dec_min; next)
    sec_match?(t) || (t.dec_sec; next)
    break
  end

  t.time.translate(from.zone)
end

#rough_frequencyObject



434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
# File 'lib/fugit/cron.rb', line 434

def rough_frequency

  slots = SLOTS
    .collect { |k, v0, v1|
      a = (k == :days) ? rough_days : instance_variable_get("@#{k}")
      [ k, v0, v1, a ] }

  slots.each do |k, v0, _, a|
    next if a == [ 0 ]
    break if a != nil
    return v0 if a == nil
  end

  slots.each do |k, v0, v1, a|
    next unless a && a.length > 1
    return (a + [ a.first + v1 ])
      .each_cons(2)
      .collect { |a0, a1| a1 - a0 }
      .select { |d| d > 0 } # weed out zero deltas
      .min * v0
  end

  slots.reverse.each do |k, v0, v1, a|
    return v0 * v1 if a && a.length == 1
  end

  1 # second
end

#sec_match?(nt) ⇒ Boolean



174
# File 'lib/fugit/cron.rb', line 174

def sec_match?(nt); ( ! @seconds) || @seconds.include?(nt.sec); end

#to_aObject



491
492
493
494
# File 'lib/fugit/cron.rb', line 491

def to_a

  [ @seconds, @minutes, @hours, @monthdays, @months, @weekdays ]
end

#to_cron_sObject



74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/fugit/cron.rb', line 74

def to_cron_s

  @cron_s ||= [
    @seconds == [ 0 ] ? nil : (@seconds || [ '*' ]).join(','),
    (@minutes || [ '*' ]).join(','),
    (@hours || [ '*' ]).join(','),
    (@monthdays || [ '*' ]).join(','),
    (@months || [ '*' ]).join(','),
    weekdays_to_cron_s,
    @timezone ? @timezone.name : nil
      ].compact.join(' ')
end

#to_hObject



496
497
498
499
500
501
502
503
504
# File 'lib/fugit/cron.rb', line 496

def to_h

  { seconds: @seconds,
    minutes: @minutes,
    hours: @hours,
    monthdays: @monthdays,
    months: @months,
    weekdays: @weekdays }
end

#weekday_hash_match?(nt, hsh) ⇒ Boolean



176
177
178
179
180
181
182
183
184
185
186
# File 'lib/fugit/cron.rb', line 176

def weekday_hash_match?(nt, hsh)

  return false unless hsh.is_a?(Integer)

  phsh, nhsh = nt.wday_in_month
    #
    # positive wday, from the beginning of the month
    # negative wday, from the end of the month, -1 == last

  (hsh == phsh) || (hsh == nhsh)
end

#weekday_match?(nt) ⇒ Boolean



194
195
196
197
198
199
200
201
202
# File 'lib/fugit/cron.rb', line 194

def weekday_match?(nt)

  @weekdays.nil? ||
  @weekdays.find { |wd, hom|
    (nt.wday == wd) &&
    (hom.nil? ||
     weekday_modulo_match?(nt, hom) ||
     weekday_hash_match?(nt, hom)) }
end

#weekday_modulo_match?(nt, mod) ⇒ Boolean



188
189
190
191
192
# File 'lib/fugit/cron.rb', line 188

def weekday_modulo_match?(nt, mod)

  mod.is_a?(Array) &&
  ((nt.rweek % mod[0]) == (mod[1] % mod[0]))
end

#within(time_range, time_end = nil) ⇒ Object

Returns an array of EtOrbi::EoTime instances that correspond to the occurrences of the cron within the given time range



385
386
387
388
389
390
391
392
393
394
# File 'lib/fugit/cron.rb', line 385

def within(time_range, time_end=nil)

  sta, ned =
    time_range.is_a?(::Range) ? [ time_range.begin, time_range.end ] :
    [ ::EtOrbi.make_time(time_range), ::EtOrbi.make_time(time_end) ]

  CronIterator
    .new(self, :next_time, sta)
    .take_while { |eot| eot.to_t < ned }
end