Class: CronCalc::Parser

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

Overview

The Parser class provides functionality to parse and calculate occurrences of cron jobs within a given time period. It interprets cron strings and calculates when cron jobs will occur

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cron_string) ⇒ Parser

Returns a new instance of Parser.



47
48
49
50
51
52
53
54
# File 'lib/cron_calc.rb', line 47

def initialize(cron_string)
  @cron_string = cron_string

  raise 'Cron expression is not supported or invalid' unless cron_string_valid?

  @cron_string = normalize_with(cron_string, PREDEFINED_DEFINITIONS) if @cron_string.start_with? '@'
  @cron_parts = split_cron_string
end

Instance Attribute Details

#cron_partsObject (readonly)

Returns the value of attribute cron_parts.



45
46
47
# File 'lib/cron_calc.rb', line 45

def cron_parts
  @cron_parts
end

#cron_stringObject (readonly)

Returns the value of attribute cron_string.



45
46
47
# File 'lib/cron_calc.rb', line 45

def cron_string
  @cron_string
end

Instance Method Details

#in(period) ⇒ Array<Time>

Calculates cron job occurrences within a given time period.

Parameters:

  • period (Range)

    The time period for which to calculate cron job occurrences.

Returns:

  • (Array<Time>)

    An array of Time instances representing each occurrence.



59
60
61
# File 'lib/cron_calc.rb', line 59

def in(period)
  occurrences(period)
end

#last(count = 1, before: Time.now, max_years: 5) ⇒ Array<Time>

Calculates the last ‘n’ occurrences of the cron job until a given end time.

Parameters:

  • count (Integer) (defaults to: 1)

    The number of past occurrences to calculate.

  • before (Time) (defaults to: Time.now)

    The end time until which to calculate occurrences.

  • max_years (Integer) (defaults to: 5)

    The maximum number of years to consider for the period.

Returns:

  • (Array<Time>)

    An array of the last ‘n’ occurrences.



80
81
82
83
84
85
86
# File 'lib/cron_calc.rb', line 80

def last(count = 1, before: Time.now, max_years: 5)
  occurrences(
    (before - (60 * 60 * 24 * 365 * max_years))..before,
    count,
    reverse: true
  )
end

#next(count = 1, after: Time.now, max_years: 5) ⇒ Array<Time>

Calculates the next ‘n’ occurrences of the cron job from a given start time.

Parameters:

  • count (Integer) (defaults to: 1)

    The number of occurrences to calculate.

  • after (Time) (defaults to: Time.now)

    The start time from which to calculate occurrences.

  • max_years (Integer) (defaults to: 5)

    The maximum number of years to consider for the period.

Returns:

  • (Array<Time>)

    An array of the next ‘n’ occurrences.



68
69
70
71
72
73
# File 'lib/cron_calc.rb', line 68

def next(count = 1, after: Time.now, max_years: 5)
  occurrences(
    after..(after + (60 * 60 * 24 * 365 * max_years)),
    count
  )
end