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/devandbundle 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¶
-
Add the jobs gems to your
Gemfile:The
:defaultgroup loads the gems in your app. The:cligroup adds thehanami jobscommands, which load only when you run thehanamicommand, not in the web process. -
Install the bundle:
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¶
-
Generate the migrations:
The command writes two migrations into
config/db/migrate/, whose names end in_create_mankai_jobs_tables.rband_add_mankai_jobs_controls.rb. -
Run the migrations:
Step 6: Enqueue the job¶
-
Open a console:
-
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:
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:
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.
-
Add a
workerline toProcfile.dev, whichbin/devreads: -
Run
bin/dev. The output shows lines from bothwebandworker.
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.
-
Create
app/actions/signups/create.rbwith 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 -
Add a route for the action to
config/routes.rb, inside theroutesblock: -
With
bin/devrunning, send a request in another terminal:The response is
Enqueued, and theworkeroutput showsNew 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 startloggedNew signup: 123.bin/devstarts bothwebandworker.- The
curlrequest returnedEnqueued, and the worker loggedNew signup: 42. - In the console,
Hanami.app["queue.backend"].countsreturns at leastfinished: 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¶
- How jobs work: the job lifecycle and the backends.
- Define and enqueue jobs: arguments, results, and callbacks.
- Make jobs reliable: retries, unique jobs, and safe re-runs.
- Test jobs: test jobs and enqueues without a worker.
- mankai-jobs reference: every setting and result.