2024-04-29 00:17:15 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2020-11-13 14:34:53 +01:00
|
|
|
class Cron::CronJob < ApplicationJob
|
2020-03-28 16:45:16 +01:00
|
|
|
queue_as :cron
|
2020-04-01 15:26:46 +02:00
|
|
|
class_attribute :schedule_expression
|
2020-03-28 16:45:16 +01:00
|
|
|
|
|
|
|
class << self
|
2022-07-21 15:28:28 +02:00
|
|
|
def schedulable?
|
2024-04-10 18:02:17 +02:00
|
|
|
ENV['CRON_JOBS_DISABLED'].blank?
|
2022-07-21 15:28:28 +02:00
|
|
|
end
|
|
|
|
|
2020-03-28 16:45:16 +01:00
|
|
|
def schedule
|
|
|
|
remove if cron_expression_changed?
|
2024-04-04 16:38:23 +02:00
|
|
|
|
|
|
|
if !scheduled?
|
2024-04-10 18:02:17 +02:00
|
|
|
if queue_adapter_name == "sidekiq"
|
2024-04-04 16:38:23 +02:00
|
|
|
Sidekiq::Cron::Job.create(name: name, cron: cron_expression, class: name)
|
|
|
|
else
|
|
|
|
set(cron: cron_expression).perform_later
|
|
|
|
end
|
|
|
|
end
|
2020-03-28 16:45:16 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def remove
|
2024-04-04 16:38:23 +02:00
|
|
|
enqueued_cron_job.destroy if scheduled?
|
2020-03-28 16:45:16 +01:00
|
|
|
end
|
|
|
|
|
2020-04-01 15:26:46 +02:00
|
|
|
def display_schedule
|
|
|
|
pp "#{name}: #{schedule_expression} cron(#{cron_expression})"
|
|
|
|
end
|
|
|
|
|
2020-03-28 16:45:16 +01:00
|
|
|
def scheduled?
|
2024-04-04 16:38:23 +02:00
|
|
|
enqueued_cron_job.present?
|
2020-03-28 16:45:16 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def cron_expression_changed?
|
2024-04-04 16:38:23 +02:00
|
|
|
scheduled? && enqueued_cron_job.cron != cron_expression
|
|
|
|
end
|
|
|
|
|
|
|
|
def enqueued_cron_job
|
2024-04-10 18:02:17 +02:00
|
|
|
if queue_adapter_name == "sidekiq"
|
2024-04-04 16:38:23 +02:00
|
|
|
sidekiq_cron_job
|
|
|
|
else
|
|
|
|
delayed_job
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def sidekiq_cron_job
|
|
|
|
Sidekiq::Cron::Job.find(name)
|
2020-03-28 16:45:16 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def delayed_job
|
|
|
|
Delayed::Job
|
|
|
|
.where('handler LIKE ?', "%job_class: #{name}%")
|
|
|
|
.first
|
|
|
|
end
|
2020-04-01 15:26:46 +02:00
|
|
|
|
|
|
|
def cron_expression
|
|
|
|
Fugit.do_parse(schedule_expression, multi: :fail).to_cron_s
|
|
|
|
end
|
2020-03-28 16:45:16 +01:00
|
|
|
end
|
|
|
|
end
|