Schedule and monitor jobs¶
This guide shows you how to run jobs on a schedule, wrap every job run with your own code, and get notified when jobs fail. It assumes that you can already define and enqueue jobs. Recurring tasks need the SQL backend; see Run jobs on the SQL backend.
Schedule recurring jobs¶
A recurring task enqueues a job on a schedule. Only the SQL backend runs recurring tasks, in the
scheduler process that hanami jobs start runs. To add a recurring task, follow these steps:
-
Create
config/recurring.ymlwith one section per environment. The following file sends a digest every morning at 07:00 UTC and runs a cleanup job every 5 minutes on thelowqueue: -
Load the file in the provider's
configureblock, inconfig/providers/queue.rb:config.recurring = Mankai::Jobs::Recurring.load_yaml( File.join(Hanami.app.root, "config/recurring.yml"), env: Hanami.env )If the file doesn't exist, the app has no recurring tasks.
-
Restart
bundle exec hanami jobs start. The command now also starts a scheduler.
Each task needs a job and a schedule. A schedule is a cron line, such as "0 7 * * *", or a phrase,
such as every 5 minutes or every day at 7am. Schedules use UTC unless they name a time zone, as in
"0 7 * * * Europe/Berlin". For every key, see
Recurring tasks in the mankai-jobs reference.
You can also set config.recurring to a hash with the same keys, instead of loading a file.
Keep the following behavior in mind:
- An invalid definition raises an error at boot.
- Runs that were due while no scheduler was running are skipped, not run later.
- The scheduler stores each run directly, without the enqueuer. The job's contract still checks the
arguments, but
before_enqueueandafter_enqueuecallbacks, enqueue middleware, and themankai.jobs.enqueueevent are skipped.capture_localerecords no locale, so the job runs in the default locale.
To add or remove tasks without a deploy, set dynamic_recurring_tasks: true on the SQL backend and
call backend.schedule_recurring. See
Administration API.
Wrap every job run¶
Perform middleware runs around every job, so use it for concerns that all jobs share, such as
metrics or tracing. A perform middleware is an object with call(envelope, job) that yields to run
the job and returns the result of yield. To add one, follow these steps:
-
Define the middleware. The following class reports how long each job takes. Replace
Metricswith your metrics client: -
Add it to the provider's
configureblock:
To change or cancel jobs as they're enqueued, use enqueue middleware instead: an object with
call(envelope) that returns an Envelope, which it can change, or a Failure to cancel the enqueue.
Add it with config.enqueue_middleware. For the built-in middleware, see
Middleware.
If your app has slices, set middleware on the app's provider. Workers run every job with the app
provider's settings. See Enqueue jobs from a slice.
Subscribe to job events¶
mankai-jobs publishes events on the app's notifications bus, such as mankai.jobs.fail when a job
fails permanently. Use them for metrics and alerts instead of parsing logs.
The events are registered when the queue provider starts, and dry-monitor raises an error if you
subscribe to an event before it's registered. Subscribe in the provider's after(:start) block. The
following provider logs every job that fails permanently:
# config/providers/queue.rb
Hanami.app.register_provider(:queue, namespace: true, from: :mankai_jobs, source: :jobs) do
configure do |config|
# ...
end
after(:start) do
target["notifications"].subscribe(:"mankai.jobs.fail") do |event|
envelope = event[:envelope]
target["logger"].error("Job #{envelope.job} (#{envelope.id}) failed: #{event[:outcome].error&.message}")
end
end
end
The after(:start) block runs wherever the provider starts: in the web process, in the console when
you first use a queue. component, and in hanami jobs start, with or without --prepare. To
subscribe from another provider, call target.start(:queue) in that provider's start step first.
Jobs that fail because their worker crashed don't publish mankai.jobs.fail. To hear about them,
subscribe to mankai.jobs.sql.fail_claims the same way. For every event and its payload, see
Events in the mankai-jobs reference and
Events in the mankai-jobs-sql reference.
Report job errors¶
To send job errors to an error tracker, set config.error_reporter to a callable. The runner calls it
with the error and a context hash when a job fails permanently, or when a rule with report: true
matches. The following setting sends errors to an error tracker. Replace ErrorTracker with your
tracker's client:
The context is a hash with the keys job, id, attempts, and status.
What's next¶
- Make jobs reliable: retries, unique jobs, and concurrency limits.
- Troubleshoot: fix common problems with jobs.
- mankai-jobs reference: every setting, result, and event.