Skip to content
Edit this page View source of this page

Define and enqueue jobs

This guide shows you how to write a job class, pass it arguments, return a result, and enqueue it from your app. It assumes that you've set up the queue provider, as described in Install Mankai. For the ideas behind jobs, such as job keys, envelopes, and backends, see How jobs work. For every setting, see the mankai-jobs reference.

The examples use Bookshelf as the app module. Replace it with your app's module.

Create a base job class

Create one base job class for your app, just as Hanami apps have a base action in app/action.rb. Create app/job.rb with the following content:

# app/job.rb
# auto_register: false
require "mankai/jobs"

module Bookshelf
  class Job < Mankai::Jobs::Job
  end
end

The auto_register: false comment stops Hanami from registering the base class as a job. Subclasses inherit settings, rules, and callbacks, so put shared behavior on the base class.

Define a job

A job is a class in app/jobs/ that implements #call. Hanami registers it under its job key, the jobs namespace plus the filename. The following job, in app/jobs/send_welcome.rb, has the job key jobs.send_welcome:

# app/jobs/send_welcome.rb
module Bookshelf
  module Jobs
    class SendWelcome < Bookshelf::Job
      config.queue = "mailers"
      config.max_attempts = 3

      contract do
        required(:user_id).filled(:integer)
      end

      retry_on Net::ReadTimeout, attempts: 5, wait: :exponential
      discard_on :user_missing, report: true

      include Deps["repos.user_repo", "mailers.welcome"]

      def call(user_id:)
        user = user_repo.find(user_id) or return Failure(:user_missing)
        welcome.deliver(user:)
        Success()
      end
    end
  end
end

The class declares the following:

  • config.queue and config.max_attempts are job settings. The job runs on the mailers queue and runs at most three times for errors that no rule matches.
  • contract checks the arguments. See Pass arguments.
  • retry_on and discard_on are rules that decide what happens after an error. See Make jobs reliable.
  • Deps injects the job's collaborators, as in any Hanami component.
  • #call receives the arguments as keywords and returns a result. See Return a result.

Caution: Outside tests, Hanami creates each component once and reuses it, so several threads might run the same job instance at the same time. Don't keep per-run state in instance variables.

For every job setting, see Job settings in the mankai-jobs reference.

Pass arguments

Job arguments are stored as JSON, so by default they must survive a JSON round trip unchanged: strings, integers, finite floats, booleans, nil, arrays, and hashes with string or symbol keys. Pass IDs, not records. The enqueuer rejects any other value with :unserializable_args.

To check the arguments, declare a contract, a dry-schema JSON schema. It runs when the job is enqueued and again before it runs. The following contract requires user_id and allows locale:

contract do
  required(:user_id).filled(:integer)
  optional(:locale).filled(:string)
end

If the arguments don't match the contract, the enqueuer returns Failure[:invalid_args, errors] and doesn't store the job.

Caution: A contract drops every argument that it doesn't declare, without an error. If #call takes locale: but the contract leaves it out, the job runs without it. Declare every keyword that #call takes.

Optional: To accept more types, such as Time and Date, set the serializers provider setting in config/providers/queue.rb:

config.serializers = [Mankai::Jobs::Serializers::Time, Mankai::Jobs::Serializers::Date]

For the other serializers, see Serializers.

Return a result

The value that #call returns tells the runner what happens next:

Return value Result
Success(...), or any value that isn't a Result The job succeeds.
discard(reason) The job finishes as discarded, not failed.
retry_later(reason, wait: seconds) The job runs again after wait seconds, and uses up an attempt.
snooze(seconds) The job runs again after seconds, without using up an attempt.
Failure(reason), or a raised exception The runner applies the job's discard_on and retry_on rules.

If no rule matches a failure, the runner retries the job with backoff until it reaches max_attempts, then records it as failed. The default max_attempts is 1, so by default a failed job isn't retried. To set up retries, see Retry failed jobs.

Add callbacks

A callback runs your code at a point in the job's life. Each callback takes a method name or a block, and runs on the job instance. The following callback cancels the enqueue of a report that was already sent:

before_enqueue do |envelope|
  Failure(:already_sent) if report_sent?(envelope.args["report_id"])
end

The following callbacks are available:

Callback Runs
before Before #call. Return a Failure to stop the run.
after After a successful #call.
around Around #call. The block must call run.call and return its result. Use it for metrics or tracing.
after_discard After the job is discarded, or fails with no attempts left.
before_enqueue Before the job is stored. Return a Failure to cancel the enqueue, or a changed envelope to store instead.
after_enqueue After the job is stored.

For each callback's block arguments, see Callbacks.

Run an operation as a job

To turn another kind of object into a job, such as a dry-operation, include Mankai::Jobs::Performable. Define the class inside your app's Jobs module in app/jobs/, so that Hanami can load it:

# app/jobs/import_feed.rb
module Bookshelf
  module Jobs
    class ImportFeed < Bookshelf::Operation
      include Mankai::Jobs::Performable
      config.queue = "imports"

      def call(feed_id:)
        feed = step fetch(feed_id)
        step store(feed)
      end
    end
  end
end

The operation keeps its own API, and you can enqueue it by its job key, jobs.import_feed. The runner treats the Success or Failure that the operation returns like any other result.

Deliver mail in a job

Mankai::Jobs::MailerJob delivers a Hanami mailer in a job. To use it, follow these steps:

  1. Subclass MailerJob in your app. The following class also retries deliveries that raise a network error:

    # app/jobs/deliver_mail.rb
    module Bookshelf
      module Jobs
        class DeliverMail < Mankai::Jobs::MailerJob
          retry_on "Net::SMTPServerBusy", "Net::ReadTimeout", attempts: 5, wait: :exponential
    
          def initialize(mailers: Bookshelf::App, **) = super
        end
      end
    end
    
  2. Enqueue a delivery with the mailer's key and its input:

    enqueuer.call(
      "jobs.deliver_mail",
      {mailer: "mailers.welcome", input: {name: "Ada", email: "[email protected]"}}
    )
    

MailerJob can deliver only mailers whose keys start with mailers.. It passes input to #deliver as keywords, so keep input JSON-safe: pass IDs and plain values, and load records inside the mailer.

MailerJob runs on the mailers queue, so make sure that a worker serves that queue, or set config.queue in your subclass. If a delivery returns an unsuccessful result, MailerJob retries it up to 5 times. If a delivery raises an exception, the job fails immediately, because max_attempts is 1. That's why the subclass in step 1 adds a retry_on rule.

Make a job resumable

A long job, such as an import, can record its progress so that it doesn't start over after an interruption. To make a job resumable, declare a steps: keyword and split the work into named steps:

def call(import_id:, steps:)
  steps.step(:download) { download(import_id) }

  steps.step(:process) do |step|
    rows(import_id, after: step.cursor).each do |row|
      process(row)
      step.advance!(row.id)
    end
  end
end

When the job runs again, it skips completed steps, and the process step resumes after the last row ID that it passed to advance!. Each call to advance! is a checkpoint. If the worker is stopping, the job pauses at its next checkpoint, without using up an attempt.

Code between checkpoints might run again after an interruption, so make each unit of work idempotent: running it twice must have the same effect as running it once. Transactional jobs can't use resumable steps.

Enqueue a job

To enqueue a job, inject the enqueuer and call it with the job key and a hash of arguments:

include Deps["queue.enqueuer"]

enqueuer.call("jobs.send_welcome", {user_id: user.id})

Pass the arguments as a positional hash. Keyword arguments are reserved for the following options:

enqueuer.call("jobs.send_welcome", {user_id: 1}, wait: 60)                 # in 60 seconds
enqueuer.call("jobs.send_welcome", {user_id: 1}, at: Time.now + 3600)      # at a time
enqueuer.call("jobs.send_welcome", {user_id: 1}, queue: "low", priority: 5) # override settings

The enqueuer returns Success(envelope), or a Failure whose first value names the problem, such as :invalid_args or :duplicate. For every failure, see Enqueue results.

If the job matters, check the result. An enqueue failure that you ignore loses the job, and nothing tells you that it happened:

result = enqueuer.call("jobs.send_welcome", {user_id: user.id})
logger.error("Could not enqueue welcome email: #{result.failure.inspect}") if result.failure?

Enqueue many jobs

To enqueue a batch, call call_many with a list of job keys and arguments:

enqueuer.call_many([
  ["jobs.send_welcome", {user_id: 1}],
  ["jobs.send_welcome", {user_id: 2}]
])

If any request fails, call_many enqueues nothing. Otherwise, it returns Success with one entry per request. For a unique job that's already pending, the entry is a Unique::Duplicate instead of an envelope, and the rest of the batch is still stored.

Enqueue jobs from a slice

To give a slice its own enqueuer, register the queue provider in the slice, and share the app's backend:

# slices/admin/config/providers/queue.rb
Admin::Slice.register_provider(:queue, namespace: true, from: :mankai_jobs, source: :jobs) do
  configure { |config| config.backend = Hanami.app["queue.backend"] }
end

The slice's enqueuer stores slice-qualified keys, such as admin:jobs.import. Any worker can run them, and the app can enqueue a slice's job by its slice-qualified key. A slice's enqueuer turns an unqualified key, such as jobs.import, into its own slice's key.

Workers run every job with the app provider's settings. The following table shows where to set each provider setting:

Set on the app's provider Set on each slice's provider
middleware, log_jobs, retry_policy, error_reporter, and recurring enqueue_middleware, queue_prefix, and capture_locale, which apply when the slice enqueues

Give both providers the same serializers, so that workers can load what the slice stored.

What's next