lib/good_job/capsule.rb in good_job-3.21.2 vs lib/good_job/capsule.rb in good_job-3.21.3
- old
+ new
@@ -13,11 +13,11 @@
# @param configuration [GoodJob::Configuration] Configuration to use for this capsule.
def initialize(configuration: GoodJob.configuration)
@configuration = configuration
@startable = true
- @running = false
+ @started_at = nil
@mutex = Mutex.new
self.class.instances << self
end
@@ -37,11 +37,11 @@
@poller.recipients.push(-> { @multi_scheduler.create_thread({ fanout: true }) })
@cron_manager = GoodJob::CronManager.new(@configuration.cron_entries, start_on_initialize: true, executor: @shared_executor.executor) if @configuration.enable_cron?
@startable = false
- @running = true
+ @started_at = Time.current
end
end
# Shut down the thread pool executors.
# @param timeout [nil, Numeric, NONE] Seconds to wait for active threads.
@@ -52,11 +52,11 @@
# @return [void]
def shutdown(timeout: NONE)
timeout = @configuration.shutdown_timeout if timeout == NONE
GoodJob._shutdown_all([@shared_executor, @notifier, @poller, @multi_scheduler, @cron_manager].compact, timeout: timeout)
@startable = false
- @running = false
+ @started_at = nil
end
# Shutdown and then start the capsule again.
# @param timeout [Numeric, NONE] Seconds to wait for active threads.
# @return [void]
@@ -67,18 +67,32 @@
start(force: true)
end
# @return [Boolean] Whether the capsule is currently running.
def running?
- @running
+ @started_at.present?
end
# @return [Boolean] Whether the capsule has been shutdown.
def shutdown?
[@shared_executor, @notifier, @poller, @multi_scheduler, @cron_manager].compact.all?(&:shutdown?)
end
+ # @param duration [nil, Numeric] Length of idleness to check for (in seconds).
+ # @return [Boolean] Whether the capsule is idle
+ def idle?(duration = nil)
+ scheduler_stats = @multi_scheduler&.stats || {}
+ is_idle = scheduler_stats.fetch(:active_execution_thread_count, 0).zero?
+
+ if is_idle && duration
+ active_at = scheduler_stats.fetch(:execution_at, nil) || @started_at
+ active_at.nil? || (Time.current - active_at >= duration)
+ else
+ is_idle
+ end
+ end
+
# Creates an execution thread(s) with the given attributes.
# @param job_state [Hash, nil] See {GoodJob::Scheduler#create_thread}.
# @return [Boolean, nil] Whether the thread was created.
def create_thread(job_state = nil)
start if startable?
@@ -86,9 +100,9 @@
end
private
def startable?(force: false)
- !@running && (@startable || force)
+ !@started_at && (@startable || force)
end
end
end