process_scheduled_jobs.rb 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class BackgroundServices
  3. class Service
  4. class ProcessScheduledJobs < Service
  5. SLEEP_AFTER_JOB_START = 1.second
  6. SLEEP_AFTER_LOOP = 10.seconds
  7. attr_reader :jobs_started
  8. def initialize(...)
  9. @jobs_started = Concurrent::Hash.new
  10. super
  11. end
  12. def launch
  13. loop do
  14. break if BackgroundServices.shutdown_requested
  15. Rails.logger.info 'ProcessScheduledJobs running...'
  16. run_jobs
  17. interruptible_sleep SLEEP_AFTER_LOOP
  18. end
  19. # Wait for threads to finish for a clean shutdown.
  20. jobs_started.each(&:join)
  21. end
  22. private
  23. def run_jobs
  24. scope.each do |job|
  25. break if BackgroundServices.shutdown_requested
  26. result = Manager.new(job, jobs_started).run
  27. interruptible_sleep SLEEP_AFTER_JOB_START if result
  28. end
  29. end
  30. def scope
  31. # changes in sub threads will not update the rails
  32. # cache so we need to be sure that the scheduler get
  33. # updated last_run values, so they don't run all the time
  34. # https://github.com/zammad/zammad/issues/4167
  35. Scheduler.clear_query_caches_for_current_thread
  36. Scheduler.where(active: true).reorder(prio: :asc)
  37. end
  38. end
  39. end
  40. end