2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-10-02 12:01:53 +08:00
|
|
|
class Jobs::Onceoff < ::Jobs::Base
|
2016-04-08 02:32:31 +08:00
|
|
|
sidekiq_options retry: false
|
|
|
|
|
2024-07-25 13:30:56 +08:00
|
|
|
class << self
|
2024-07-25 15:52:42 +08:00
|
|
|
@@onceoff_job_klasses = Set.new
|
2024-07-25 13:30:56 +08:00
|
|
|
|
|
|
|
def inherited(klass)
|
2024-07-25 15:52:42 +08:00
|
|
|
@@onceoff_job_klasses << klass
|
|
|
|
end
|
|
|
|
|
|
|
|
def onceoff_job_klasses
|
|
|
|
@@onceoff_job_klasses
|
2024-07-25 13:30:56 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2016-04-08 02:32:31 +08:00
|
|
|
def self.name_for(klass)
|
2023-01-21 02:52:49 +08:00
|
|
|
klass.name.sub(/\AJobs\:\:/, "")
|
2016-04-08 02:32:31 +08:00
|
|
|
end
|
|
|
|
|
2016-04-13 02:47:38 +08:00
|
|
|
def running_key_name
|
|
|
|
"#{self.class.name}:running"
|
|
|
|
end
|
|
|
|
|
2016-04-08 02:32:31 +08:00
|
|
|
# Pass `force: true` to force it happen again
|
|
|
|
def execute(args)
|
|
|
|
job_name = self.class.name_for(self.class)
|
2019-12-03 17:05:53 +08:00
|
|
|
has_lock = Discourse.redis.setnx(running_key_name, Time.now.to_i)
|
2016-04-08 02:32:31 +08:00
|
|
|
|
2016-04-13 02:47:38 +08:00
|
|
|
# If we can't get a lock, just noop
|
|
|
|
if args[:force] || has_lock
|
|
|
|
begin
|
2016-04-12 21:08:10 +08:00
|
|
|
return if OnceoffLog.where(job_name: job_name).exists? && !args[:force]
|
2016-04-08 03:07:24 +08:00
|
|
|
execute_onceoff(args)
|
2018-09-19 18:22:54 +08:00
|
|
|
OnceoffLog.create!(job_name: job_name)
|
2016-04-13 02:47:38 +08:00
|
|
|
ensure
|
2019-12-03 17:05:53 +08:00
|
|
|
Discourse.redis.del(running_key_name) if has_lock
|
2016-04-08 03:07:24 +08:00
|
|
|
end
|
2016-04-08 02:32:31 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.enqueue_all
|
2016-04-08 03:07:24 +08:00
|
|
|
previously_ran = OnceoffLog.pluck(:job_name).uniq
|
|
|
|
|
2024-07-25 13:30:56 +08:00
|
|
|
self.onceoff_job_klasses.each do |klass|
|
|
|
|
job_name = name_for(klass)
|
|
|
|
Jobs.enqueue(job_name.underscore.to_sym) if previously_ran.exclude?(job_name)
|
|
|
|
end
|
2016-04-08 02:32:31 +08:00
|
|
|
end
|
|
|
|
end
|