2017-04-04 05:44:25 -04:00
|
|
|
module Gitlab
|
|
|
|
module Ci
|
|
|
|
class CronParser
|
|
|
|
VALID_SYNTAX_SAMPLE_TIME_ZONE = 'UTC'.freeze
|
|
|
|
VALID_SYNTAX_SAMPLE_CRON = '* * * * *'.freeze
|
|
|
|
|
2017-04-04 12:54:45 -04:00
|
|
|
def initialize(cron, cron_timezone = 'UTC')
|
2017-04-04 05:44:25 -04:00
|
|
|
@cron = cron
|
2017-05-03 11:23:20 -04:00
|
|
|
@cron_timezone = ActiveSupport::TimeZone.find_tzinfo(cron_timezone).name
|
2017-04-04 05:44:25 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def next_time_from(time)
|
2017-04-05 03:47:20 -04:00
|
|
|
@cron_line ||= try_parse_cron(@cron, @cron_timezone)
|
2017-05-10 11:48:09 -04:00
|
|
|
@cron_line.next_time(time).utc.in_time_zone(Time.zone) if @cron_line.present?
|
2017-04-04 05:44:25 -04:00
|
|
|
end
|
|
|
|
|
2017-04-04 06:14:49 -04:00
|
|
|
def cron_valid?
|
|
|
|
try_parse_cron(@cron, VALID_SYNTAX_SAMPLE_TIME_ZONE).present?
|
|
|
|
end
|
|
|
|
|
2017-04-04 12:54:45 -04:00
|
|
|
def cron_timezone_valid?
|
|
|
|
try_parse_cron(VALID_SYNTAX_SAMPLE_CRON, @cron_timezone).present?
|
2017-04-04 05:44:25 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2017-05-03 11:23:20 -04:00
|
|
|
# NOTE:
|
|
|
|
# cron_timezone can only accept timezones listed in TZInfo::Timezone.
|
|
|
|
# Aliases of Timezones from ActiveSupport::TimeZone are NOT accepted,
|
|
|
|
# because Rufus::Scheduler only supports TZInfo::Timezone.
|
|
|
|
#
|
|
|
|
# For example, those codes have the same effect.
|
|
|
|
# Time.zone = 'Pacific Time (US & Canada)' (ActiveSupport::TimeZone)
|
|
|
|
# Time.zone = 'America/Los_Angeles' (TZInfo::Timezone)
|
|
|
|
#
|
|
|
|
# However, try_parse_cron only accepts the latter format.
|
|
|
|
# try_parse_cron('* * * * *', 'Pacific Time (US & Canada)') -> Doesn't work
|
|
|
|
# try_parse_cron('* * * * *', 'America/Los_Angeles') -> Works
|
|
|
|
# If you want to know more, please take a look
|
|
|
|
# https://github.com/rails/rails/blob/master/activesupport/lib/active_support/values/time_zone.rb
|
2017-04-04 12:54:45 -04:00
|
|
|
def try_parse_cron(cron, cron_timezone)
|
2017-05-03 11:23:20 -04:00
|
|
|
cron_line = Rufus::Scheduler.parse("#{cron} #{cron_timezone}")
|
|
|
|
cron_line if cron_line.is_a?(Rufus::Scheduler::CronLine)
|
2017-04-04 08:18:51 -04:00
|
|
|
rescue
|
|
|
|
# noop
|
2017-04-04 05:44:25 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2017-04-04 12:59:24 -04:00
|
|
|
end
|