Module: Utility::Cron

Defined in:
lib/utility/cron.rb

Overview

Class Method Summary collapse

Class Method Details

.check(expr) ⇒ Object

Raises:

  • (StandardError)


22
23
24
25
26
27
28
# File 'lib/utility/cron.rb', line 22

def self.check(expr)
  raise StandardError.new("Unsupported expression #{expr} with #") if expr.include?('#')
  raise StandardError.new("Unsupported expression #{expr} with L") if expr.include?('L')
  raise StandardError.new("Unsupported expression #{expr} with W") if expr.include?('W') && !expr.include?('WED')

  expr
end

.quartz_to_crontab(expression) ⇒ Object

Raises:

  • (StandardError)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/utility/cron.rb', line 30

def self.quartz_to_crontab(expression)
  @seconds = '*'
  @minutes = '*'
  @hours = '*'
  @day_of_month = '*'
  @month = '*'
  @day_of_week = '*'
  @year = '*'

  # ? is not supported
  converted_expression = expression.tr('?', '*')

  matched = false
  converted_expression.match(CRON_REGEXP) { |m|
    @seconds = m[2]
    @minutes = m[3]
    @hours = m[4]
    @day_of_month = check(m[5])
    @month = check(m[6])
    @day_of_week = scheduler_dow_to_crontab(check(m[7])).to_s
    @year = m[9]
    matched = true
  }

  raise StandardError.new("Unknown format #{expression}") unless matched

  # Unix cron has five: minute, hour, day, month, and dayofweek
  # Quartz adds seconds and year
  converted_expression = "#{@minutes} #{@hours} #{@day_of_month} #{@month} #{@day_of_week}"

  Utility::Logger.debug("Converted Quartz Cron expression '#{expression}' to Standard Cron Expression '#{converted_expression}'")

  converted_expression
end

.scheduler_dow_to_crontab(day) ⇒ Object

As described above, Quartz uses 1-7 for days of the week, starting with Sunday, while Unix cron uses 0-6, starting with Monday, and also 7 as an extra non-standard index for Sunday. (see en.wikipedia.org/wiki/Cron for more details) This means that we need to shift the Quartz day of week that are between 1 and 7 by minus one, but we also allow 0 in case it’s not a quartz expression but already the cron standard. See also the code in connectors-python that does the same thing: github.com/elastic/connectors-python/blob/main/connectors/quartz.py



71
72
73
74
75
76
77
78
79
# File 'lib/utility/cron.rb', line 71

def self.scheduler_dow_to_crontab(day)
  unless /\d/.match?(day)
    return day
  end
  if day.to_i <= 0
    return day
  end
  day.to_i - 1
end