How Sidekiq Iteration works
masterSidekiq Iteration allows you to define jobs that can be safely interrupted and resumed. Instead of a single massive #perform method, you split the job into two parts: an Enumerator (to define the data source and cursor) and an Action (to define what to do with each item).
The Workflow
build_enumerator(cursor:): This method is called to construct anEnumerator. It uses the providedcursorto know where to start.- Iteration: The job iterates over the items provided by the enumerator.
- Interruption: If the process receives a
SIGTERM(graceful termination signal), the job completes its current iteration, checksjob_should_exit?, and then stops. - Resumption: Upon stopping, the job re-enqueues itself with the latest
cursor_position. When the job runs again, thecursorpassed tobuild_enumeratorwill reflect the last successfully processed position, allowing the job to pick up exactly where it left off.
class NotifyUsers
include Sidekiq::Job
include SidekiqIteration::Iteration
def build_enumerator(cursor:)
active_record_records_enumerator(User.all, cursor: cursor)
end
def each_iteration(user)
user.notify_about_something
end
end