Skip to content
Edit this page View source of this page

Run your first background job

In this tutorial, you add background jobs to a Hanami app, enqueue a job from the console, and watch a worker process run it. Then you enqueue the job from an action. You don't need experience with background job libraries. Allow about 15 minutes.

This tutorial uses the SQL backend, which stores jobs in your app's database. The job that you enqueue from the console then runs in a separate worker process. The built-in :memory, :inline, and :async backends can't do this, because they run jobs inside the process that enqueued them.

Before you begin

You need the following:

  • A Hanami 3 app with a configured database.
  • An app that starts with bin/dev and bundle exec hanami console.
  • One of these databases: PostgreSQL, MySQL 8 or later, MariaDB 10.6 or later, or SQLite.

On MySQL and MariaDB, add fractional_seconds=true to the database URL before you start. On SQLite, set a busy handler on the connection, as shown in SQLite in the mankai-jobs-sql reference.

Run all commands from the app's root directory. The examples use Bookshelf as the app module. Replace it with your app's module.

Step 1: Add the gems

  1. Add the jobs gems to your Gemfile:

    # Gemfile
    gem "mankai-jobs", group: [:default, :cli]
    gem "mankai-jobs-sql", group: [:default, :cli]
    

    The :default group loads the gems in your app. The :cli group adds the hanami jobs commands, which load only when you run the hanami command, not in the web process.

  2. Install the bundle:

    bundle install
    

Step 2: Create a base job class

Your jobs inherit from a base class, just as actions inherit from 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.

Step 3: Register the queue provider

Create config/providers/queue.rb with the following content:

# config/providers/queue.rb
require "mankai/jobs"
require "mankai/jobs/sql"

Hanami.app.register_provider(:queue, namespace: true, from: :mankai_jobs, source: :jobs) do
  configure do |config|
    config.backend = Hanami.env?(:test) ? :memory : Mankai::Jobs::SQL.backend
  end
end

The provider registers the queue.enqueuer component, which you use to enqueue jobs, and four other components that the mankai-jobs reference lists. Tests use the memory backend, where jobs wait until the test runs them. Every other environment uses the SQL backend.

The provider is named queue, not jobs, so its components can't be mistaken for jobs.

Step 4: Write a job

Create app/jobs/log_signup.rb with the following content:

# app/jobs/log_signup.rb
module Bookshelf
  module Jobs
    class LogSignup < Bookshelf::Job
      include Deps["logger"]

      def call(user_id:)
        logger.info("New signup: #{user_id}")
        Success()
      end
    end
  end
end

Hanami registers the job under the key jobs.log_signup: the jobs namespace plus the filename. You use this key to enqueue the job. Like any component, the job gets its collaborators through Deps.

#call receives the arguments that you enqueue as keywords. Return Success() when the work succeeds. To signal a problem, return a Failure or raise an exception; the job's retry rules then decide what happens.

Step 5: Create the jobs tables

  1. Generate the migrations:

    bundle exec hanami jobs install
    

    The command writes two migrations into config/db/migrate/, whose names end in _create_mankai_jobs_tables.rb and _add_mankai_jobs_controls.rb.

  2. Run the migrations:

    bundle exec hanami db migrate
    

Step 6: Enqueue the job

  1. Open a console:

    bundle exec hanami console
    
  2. Enqueue one job:

    result = Hanami.app["queue.enqueuer"].call("jobs.log_signup", {user_id: 123})
    result.success? # => true
    envelope = result.value!
    envelope.job    # => "jobs.log_signup"
    

    The enqueuer returns a Result. On success, its value is the envelope, the stored form of the job.

Pass the job's arguments as a hash. Arguments must be plain JSON values by default, so pass user_id: 123, not a User object.

If the result is a failure, its first value names the problem. The following table lists the most common failures:

Failure Cause
:unknown_job The key doesn't resolve to a job. Check the filename and the module names.
:invalid_args The job's contract rejected the arguments.
:unserializable_args An argument doesn't survive a JSON round trip. Pass IDs, not records.
:backend_error The database rejected the write. Check the database connection and the migrations.

Keep the console open for the next steps.

Step 7: Start a worker

In a second terminal, start the jobs processes:

bundle exec hanami jobs start

The command starts a supervisor process, which starts the workers, the processes that run jobs. A worker picks up your pending job and runs it. Look for the following line in the output:

New signup: 123

To stop the processes, press Ctrl+C. Stopping is graceful: a running job gets a few seconds to finish, and jobs that haven't run yet stay in the database for the next start.

Step 8: Run the worker with the app

Jobs run only while hanami jobs start is running, so start it together with the web server.

  1. Add a worker line to Procfile.dev, which bin/dev reads:

    web: bundle exec hanami server
    worker: bundle exec hanami jobs start
    
  2. Run bin/dev. The output shows lines from both web and worker.

In production, run the same command as its own process, next to the web server. See Deploy to production.

Step 9: Enqueue from an action

In a real app, you enqueue a job from the code that handles the event, such as the action that creates a user. In this step, you add a small action that enqueues the job for a user ID that it receives as a parameter.

  1. Create app/actions/signups/create.rb with the following content:

    # app/actions/signups/create.rb
    module Bookshelf
      module Actions
        module Signups
          class Create < Bookshelf::Action
            include Deps["queue.enqueuer"]
    
            def handle(request, response)
              result = enqueuer.call("jobs.log_signup", {user_id: request.params[:user_id].to_i})
    
              if result.success?
                response.status = 202
                response.body = "Enqueued"
              else
                response.status = 500
                response.body = "Could not enqueue the job: #{result.failure.first}"
              end
            end
          end
        end
      end
    end
    
  2. Add a route for the action to config/routes.rb, inside the routes block:

    post "/signups", to: "signups.create"
    
  3. With bin/dev running, send a request in another terminal:

    curl -X POST -d "user_id=42" http://localhost:2300/signups
    

    The response is Enqueued, and the worker output shows New signup: 42.

In your own app, replace the user_id parameter with the user that your signup action creates.

Enqueuing returns a Result, so a failure doesn't raise an exception inside the action. Decide what the user sees when enqueuing fails. If you ignore the failure, the job is lost without any trace.

Verify your work

Check that each of the following is true:

  • Enqueuing in the console returned a Success.
  • bundle exec hanami jobs start logged New signup: 123.
  • bin/dev starts both web and worker.
  • The curl request returned Enqueued, and the worker logged New signup: 42.
  • In the console, Hanami.app["queue.backend"].counts returns at least finished: 1. The SQL backend keeps finished jobs by default.

If the job didn't run, confirm that the worker runs in the same environment and uses the same database as the console.

What's next