service.rb 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. # Base class for background services
  3. class BackgroundServices::Service
  4. include BackgroundServices::Concerns::HasInterruptibleSleep
  5. include Mixin::RequiredSubPaths
  6. attr_reader :fork_id, :manager
  7. def self.service_name
  8. name.demodulize
  9. end
  10. # Override this method in service classes that support more than one worker process.
  11. def self.max_workers
  12. 1
  13. end
  14. def self.skip?(manager:)
  15. false
  16. end
  17. # Use this method to prepare for a service task.
  18. # This would be called only once regardless of how many workers would start.
  19. def self.pre_run
  20. run_in_service_context do
  21. pre_launch
  22. end
  23. end
  24. def self.run_in_service_context(&)
  25. Rails.application.executor.wrap do
  26. ApplicationHandleInfo.use('scheduler', &)
  27. end
  28. end
  29. def initialize(manager:, fork_id: nil)
  30. @fork_id = fork_id
  31. @manager = manager
  32. end
  33. # Use this method to run a background service.
  34. def run
  35. self.class.run_in_service_context do
  36. launch
  37. end
  38. end
  39. protected
  40. # Override this method in service classes.
  41. def launch; end
  42. class << self
  43. protected
  44. # Override this method in service classes that need to perform tasks once
  45. # before threads/workers are started.
  46. def pre_launch; end
  47. end
  48. end