Minion(3)
β¨ NAME β¨
Minion β Job queue. π
π¦ SYNOPSIS π¦
use Minion;
# Connect to backend
my $minion = Minion->new(Pg => 'postgresql://postgres@/test');
# Add tasks
$minion->add_task(something_slow => sub ($job, @args) {
sleep 5;
say 'This is a background worker process.';
});
# Enqueue jobs
$minion->enqueue(something_slow => ['foo', 'bar']);
$minion->enqueue(something_slow => [1, 2, 3] => {priority => 5});
# Perform jobs for testing
$minion->enqueue(something_slow => ['foo', 'bar']);
$minion->perform_jobs;
# Start a worker to perform up to 12 jobs concurrently
my $worker = $minion->worker;
$worker->status->{jobs} = 12;
$worker->run;
π DESCRIPTION π
Okay so Minion is a high performance job queue for the Perl programming language, and it's giving everything: multiple named queues, priorities, high priority fast lane, delayed jobs, job dependencies, job progress, job results, retries with backoff, rate limiting, unique jobs, expiring jobs, statistics, distributed workers, parallel processing, autoscaling, remote control, Mojolicious https://mojolicious.org admin ui, resource leak protection and multiple backends (such as PostgreSQL https://www.postgresql.org). No cap.
Job queues let you process time and/or computationally intensive tasks in background processes, outside of the request/response lifecycle of web applications. Among those tasks you'll commonly find image resizing, spam filtering, HTTP downloads, building tarballs, warming caches and basically everything else you can imagine that's not super fast. Like, if it's slow, put it in the background, bestie.
Take a look at our excellent documentation in Minion::Guide! It's iconic.
π EXAMPLES π
This distribution also contains a great example application you can use for inspiration. The link checker https://github.com/mojolicious/minion/tree/main/examples/linkcheck will show you how to integrate background jobs into well-structured Mojolicious applications. It's giving tutorial energy, fr fr.
π EVENTS π
Minion inherits all events from Mojo::EventEmitter and can emit the following new ones. Slay.
enqueue
$minion->on(enqueue => sub ($minion, $id) {
...
});
Emitted after a job has been enqueued, in the process that enqueued it. So like, right after you drop it in the queue.
$minion->on(enqueue => sub ($minion, $id) {
say "Job $id has been enqueued.";
});
worker
$minion->on(worker => sub ($minion, $worker) {
...
});
Emitted in the worker process after it has been created. The worker is born and immediately says hi.
$minion->on(worker => sub ($minion, $worker) {
say "Worker $$ started.";
});
β¨ ATTRIBUTES β¨
Minion implements the following attributes. Let's go through them one by one, bestie.
app
my $app = $minion->app;
$minion = $minion->app(MyApp->new);
Application for job queue, defaults to a Mojo::HelloWorld object. Note that this attribute is weakened. So like, it doesn't hold a strong reference, iykyk.
backend
my $backend = $minion->backend;
$minion = $minion->backend(Minion::Backend::Pg->new);
Backend, usually a Minion::Backend::Pg object. It's the storage baddie behind the scenes.
backoff
my $cb = $minion->backoff;
$minion = $minion->backoff(sub {...});
A callback used to calculate the delay for automatically retried jobs, defaults to (retries ** 4) + 15 (15, 16, 31, 96, 271, 640...), which means that roughly 25 attempts can be made in 21 days. Math girlie behavior, but it works.
$minion->backoff(sub ($retries) {
return ($retries ** 4) + 15 + int(rand 30);
});
missing_after
my $after = $minion->missing_after;
$minion = $minion->missing_after(172800);
Amount of time in seconds after which workers without a heartbeat will be considered missing and removed from the registry by repair, defaults to 1800 (30 minutes). If your worker ghosted, this is how long until it's officially gone.
remove_after
my $after = $minion->remove_after;
$minion = $minion->remove_after(86400);
Amount of time in seconds after which jobs that have reached the state finished and have no unresolved dependencies will be removed automatically by repair, defaults to 172800 (2 days). It is not recommended to set this value below 2 days. Don't be chaotic, keep it at least 2 days.
stuck_after
my $after = $minion->stuck_after;
$minion = $minion->stuck_after(86400);
Amount of time in seconds after which jobs that have not been processed will be considered stuck by repair and transition to the failed state, defaults to 172800 (2 days). Like, if a job is just sitting there, it gets yeeted to failed.
tasks
my $tasks = $minion->tasks;
$minion = $minion->tasks({foo => sub {...}});
Registered tasks. Your little task collection.
π METHODS π
Minion inherits all methods from Mojo::EventEmitter and implements the following new ones. Let's get into the methods, bestie.
add_task
$minion = $minion->add_task(foo => sub {...});
$minion = $minion->add_task(foo => 'MyApp::Task::Foo');
Register a task, which can be a closure or a custom Minion::Job subclass. Note that support for custom task classes is EXPERIMENTAL and might change without warning! So like, use at your own risk, bestie.
# Job with result
$minion->add_task(add => sub ($job, $first, $second) {
$job->finish($first + $second);
});
my $id = $minion->enqueue(add => [1, 1]);
my $result = $minion->job($id)->info->{result};
broadcast
my $bool = $minion->broadcast('some_command');
my $bool = $minion->broadcast('some_command', [@args]);
my $bool = $minion->broadcast('some_command', [@args], [$id1, $id2, $id3]);
Broadcast remote control command to one or more workers. It's giving group chat energy for your workers.
# Broadcast "stop" command to all workers to kill job 10025
$minion->broadcast('stop', [10025]);
# Broadcast "kill" command to all workers to interrupt job 10026
$minion->broadcast('kill', ['INT', 10026]);
# Broadcast "jobs" command to pause worker 23
$minion->broadcast('jobs', [0], [23]);
# Broadcast "spare" command to disable the feature on all workers
$minion->broadcast('spare', [0]);
class_for_task
my $class = $minion->class_for_task('foo');
Return job class for task. Note that this method is EXPERIMENTAL and might change without warning! So don't get too attached.
enqueue
my $id = $minion->enqueue('foo');
my $id = $minion->enqueue(foo => [@args]);
my $id = $minion->enqueue(foo => [@args] => {priority => 1});
Enqueue a new job with inactive state. Arguments get serialized by the backend (often with Mojo::JSON), so you shouldn't send objects and be careful with binary data, nested data structures with hash and array references are fine though. So like, no random blessed refs, but hashes and arrays are slay.
These options are currently available:
attemptsβattempts => 25
Number of times performing this job will be attempted, with a delay based on backoff after the first attempt, defaults to 1. So like, how many chances it gets.
delayβdelay => 10
Delay job for this many seconds (from now), defaults to 0. It's not lazy, it's just scheduling.
expireβexpire => 300
Job is valid for this many seconds (from now) before it expires. After that, it's expired, periodt.
laxβlax => 1
Existing jobs this job depends on may also have transitioned to the failed state to allow for it to be processed, defaults to false. So like, it's chill about failed parents.
notesβnotes => {foo => 'bar', baz => [1, 2, 3]}
Hash reference with arbitrary metadata for this job that gets serialized by the backend (often with Mojo::JSON), so you shouldn't send objects and be careful with binary data, nested data structures with hash and array references are fine though. It's your little notes section.
parentsβparents => [$id1, $id2, $id3]
One or more existing jobs this job depends on, and that need to have transitioned to the state finished before it can be processed. So like, it waits for its parents to finish.
priorityβpriority => 5
Job priority, defaults to 0. Jobs with a higher priority get performed first. Priorities can be positive or negative, but should be in the range between 100 and -100. So like, VIP treatment.
queueβqueue => 'important'
Queue to put job in, defaults to default. Pick your lane, bestie.
foreground
my $bool = $minion->foreground($id);
Retry job in minion_foreground queue, then perform it right away with a temporary worker in this process, very useful for debugging. It's the debug baddie move.
guard
my $guard = $minion->guard('foo', 3600);
my $guard = $minion->guard('foo', 3600, {limit => 20});
Same as lock, but returns a scope guard object that automatically releases the lock as soon as the object is destroyed, or undef if aquiring the lock failed. Note: original says "aquiring", so we keep it.
# Only one job should run at a time (unique job)
$minion->add_task(do_unique_stuff => sub ($job, @args) {
return $job->finish('Previous job is still active')
unless my $guard = $minion->guard('fragile_backend_service', 7200);
...
});
# Only five jobs should run at a time and we try again later if necessary
$minion->add_task(do_concurrent_stuff => sub ($job, @args) {
return $job->retry({delay => 30})
unless my $guard = $minion->guard('some_web_service', 60, {limit => 5});
...
});
history
my $history = $minion->history;
Get history information for job queue. Like, the receipts.
These fields are currently available:
dailyβdaily => [{epoch => 12345, finished_jobs => 95, failed_jobs => 2}, ...]
Hourly counts for processed jobs from the past day. The stats are statting.
is_locked
my $bool = $minion->is_locked('foo');
Check if a lock with that name is currently active. Is it locked? Let's find out.
job
my $job = $minion->job($id);
Get Minion::Job object without making any changes to the actual job or return undef if job does not exist. It's a read-only vibe.
# Check job state
my $state = $minion->job($id)->info->{state};
# Get job metadata
my $progress = $minion->job($id)->info->{notes}{progress};
# Get job result
my $result = $minion->job($id)->info->{result};
jobs
my $jobs = $minion->jobs;
my $jobs = $minion->jobs({states => ['inactive']});
Return Minion::Iterator object to safely iterate through job information. It's the safe way to scroll through jobs.
# Iterate through jobs for two tasks
my $jobs = $minion->jobs({tasks => ['foo', 'bar']});
while (my $info = $jobs->next) {
say "$info->{id}: $info->{state}";
}
# Remove all failed jobs from a named queue
my $jobs = $minion->jobs({states => ['failed'], queues => ['unimportant']});
while (my $info = $jobs->next) {
$minion->job($info->{id})->remove;
}
# Count failed jobs for a task
say $minion->jobs({states => ['failed'], tasks => ['foo']})->total;
These options are currently available:
idsβids => ['23', '24']
List only jobs with these ids.
notesβnotes => ['foo', 'bar']
List only jobs with one of these notes.
queuesβqueues => ['important', 'unimportant']
List only jobs in these queues.
statesβstates => ['inactive', 'active']
List only jobs in these states.
tasksβtasks => ['foo', 'bar']
List only jobs for these tasks.
These fields are currently available:
argsβargs => ['foo', 'bar']
Job arguments.
attemptsβattempts => 25attemptsβ Number of times performing this job will be attempted. πchildrenβ Jobs depending on this job. Like,children => ['10026', '10027', '10028']π§createdβ Epoch time job was created.created => 784111777β°delayedβ Epoch time job was delayed to.delayed => 784111777β³expiresβ Epoch time job is valid until before it expires.expires => 784111777β°finishedβ Epoch time job was finished.finished => 784111777βidβ Job id.id => 10025πlaxβ Existing jobs this job depends on may also have failed to allow for it to be processed.lax => 0πnotesβ Hash reference with arbitrary metadata for this job.notes => {foo => 'bar', baz => [1, 2, 3]}πparentsβ Jobs this job depends on.parents => ['10023', '10024', '10025']πͺpriorityβ Job priority.priority => 3πqueueβ Queue name.queue => 'important'π¬resultβ Job result.result => 'All went well!'πretriedβ Epoch time job has been retried.retried => 784111777πretriesβ Number of times job has been retried.retries => 3πstartedβ Epoch time job was started.started => 784111777πstateβ Current job state, usually"active","failed","finished"or"inactive".state => 'inactive'π€taskβ Task name.task => 'foo'π·οΈtimeβ Server time.time => 78411177β° (note: it's78411177, not a typo, bestie!)workerβ Id of worker that is processing the job.worker => '154'π·
π lock
my $bool = $minion->lock('foo', 3600); my $bool = $minion->lock('foo', 3600, {limit => 20});
Try to acquire a named lock that will expire automatically after the given amount of time in seconds. You can release the lock manually with unlock to limit concurrency, or let it expire for rate limiting. For convenience you can also use guard to release the lock automatically, even if the job failed. π
# Only one job should run at a time (unique job)
$minion->add_task(do_unique_stuff => sub ($job, @args) {
return $job->finish('Previous job is still active')
unless $minion->lock('fragile_backend_service', 7200);
...
$minion->unlock('fragile_backend_service');
});
# Only five jobs should run at a time and we wait for our turn
$minion->add_task(do_concurrent_stuff => sub ($job, @args) {
sleep 1 until $minion->lock('some_web_service', 60, {limit => 5});
...
$minion->unlock('some_web_service');
});
# Only a hundred jobs should run per hour and we try again later if necessary
$minion->add_task(do_rate_limited_stuff => sub ($job, @args) {
return $job->retry({delay => 3600})
unless $minion->lock('another_web_service', 3600, {limit => 100});
...
$minion->unlock('another_web_service');
});
An expiration time of 0 can be used to check if a named lock could have been acquired without creating one. π΅οΈββοΈ
# Check if the lock "foo" could have been acquired
say 'Lock could have been acquired' unless $minion->lock('foo', 0);
Or to simply check if a named lock already exists you can also use is_locked. π
These options are currently available:
limitβlimit => 20β Number of shared locks with the same name that can be active at the same time, defaults to1.
π new
my $minion = Minion->new(Pg => 'postgresql://postgres@/test'); my $minion = Minion->new(Pg => Mojo::Pg->new);
Construct a new Minion object. π
π perform_jobs
$minion->perform_jobs; $minion->perform_jobs({queues => ['important']});
Perform all jobs with a temporary worker, very useful for testing. π§ͺ
# Longer version
my $worker = $minion->worker;
while (my $job = $worker->register->dequeue(0)) { $job->perform }
$worker->unregister;
These options are currently available:
idβid => '10023'β Dequeue a specific job.min_priorityβmin_priority => 3β Do not dequeue jobs with a lower priority.queuesβqueues => ['important']β One or more queues to dequeue jobs from, defaults to"default".
π perform_jobs_in_foreground
$minion->perform_jobs_in_foreground; $minion->perform_jobs_in_foreground({queues => ['important']});
Same as perform_jobs, but all jobs are performed in the current process, without spawning new processes. π¦
π οΈ repair
$minion = $minion->repair;
Repair worker registry and job queue if necessary. π§
π reset
$minion = $minion->reset({all => 1});
Reset job queue. π§Ή
These options are currently available:
allβall => 1β Reset everything.locksβlocks => 1β Reset only locks.
β³ result_p
my $promise = $minion->result_p($id); my $promise = $minion->result_p($id, {interval => 5});
Return a Mojo::Promise object for the result of a job. The state "finished" will result in the promise being "fullfilled", and the state "failed" in the promise being "rejected". This operation can be cancelled by resolving the promise manually at any time. π
# Enqueue job and receive the result at some point in the future
my $id = $minion->enqueue('foo');
$minion->result_p($id)->then(sub ($info) {
my $result = ref $info ? $info->{result} : 'Job already removed';
say "Finished: $result";
})->catch(sub ($info) {
say "Failed: $info->{result}";
})->wait;
These options are currently available:
intervalβinterval => 5β Polling interval in seconds for checking if the state of the job has changed, defaults to3.
π stats
my $stats = $minion->stats;
Get statistics for the job queue. π
# Check idle workers
my $idle = $minion->stats->{inactive_workers};
These fields are currently available:
active_jobsβactive_jobs => 100β Number of jobs in"active"state.active_locksβactive_locks => 100β Number of active named locks.active_workersβactive_workers => 100β Number of workers that are currently processing a job.delayed_jobsβdelayed_jobs => 100β Number of jobs in"inactive"state that are scheduled to run at specific time in the future or have unresolved dependencies.enqueued_jobsβenqueued_jobs => 100000β Rough estimate of how many jobs have ever been enqueued.failed_jobsβfailed_jobs => 100β Number of jobs in"failed"state.finished_jobsβfinished_jobs => 100β Number of jobs in"finished"state.inactive_jobsβinactive_jobs => 100β Number of jobs in"inactive"state.inactive_workersβinactive_workers => 100β Number of workers that are currently not processing a job.uptimeβuptime => 1000β Uptime in seconds.workersβworkers => 200;β Number of registered workers.
π unlock
my $bool = $minion->unlock('foo');
Release a named lock that has been previously acquired with lock. π
π· worker
my $worker = $minion->worker;
Build Minion::Worker object. Note that this method should only be used to implement custom workers. π οΈ
# Use the standard worker with all its features
my $worker = $minion->worker;
$worker->status->{jobs} = 12;
$worker->status->{queues} = ['important'];
$worker->run;
# Perform one job manually in a separate process
my $worker = $minion->repair->worker->register;
my $job = $worker->dequeue(5);
$job->perform;
$worker->unregister;
# Perform one job manually in this process
my $worker = $minion->repair->worker->register;
my $job = $worker->dequeue(5);
if (my $err = $job->execute) { $job->fail($err) }
else { $job->finish }
$worker->unregister;
# Build a custom worker performing multiple jobs at the same time
my %jobs;
my $worker = $minion->repair->worker->register;
do {
for my $id (keys %jobs) {
delete $jobs{$id} if $jobs{$id}->is_finished;
}
if (keys %jobs >= 4) { sleep 5 }
else {
my $job = $worker->dequeue(5);
$jobs{$job->id} = $job->start if $job;
}
} while keys %jobs;
$worker->unregister;
π₯ workers
my $workers = $minion->workers; my $workers = $minion->workers({ids => [2, 3]});
Return Minion::Iterator object to safely iterate through worker information. π
# Iterate through workers
my $workers = $minion->workers;
while (my $info = $workers->next) {
say "$info->{id}: $info->{host}";
}
These options are currently available:
idsβids => ['23', '24']β List only workers with these ids.
These fields are currently available:
idβid => 22β Worker id.hostβhost => 'localhost'β Worker host.jobsβjobs => ['10023', '10024', '10025', '10029']β Ids of jobs the worker is currently processing.notifiedβnotified => 784111777β Epoch time worker sent the last heartbeat.pidβpid => 12345β Process id of worker.startedβstarted => 784111777β Epoch time worker was started.statusβstatus => {queues => ['default', 'important']}β Hash reference with whatever status information the worker would like to share.
𧬠API
This is the class hierarchy of the Minion distribution. π
- Minion
- Minion::Backend
- Minion::Backend::Pg
- Minion::Command::minion
- Minion::Command::minion::job
- Minion::Command::minion::worker
- Minion::Iterator
- Minion::Job
- Minion::Worker
- Mojolicious::Plugin::Minion
- Mojolicious::Plugin::Minion::Admin
π BUNDLED FILES π
okay so bestie, the Minion distribution ships with a few files that come with different licenses β they got bundled in for internal use only, so don't go thinking everything in here is under one big license umbrella. Each one keeps its own. π
πΈ Minion Artwork
Copyright (C) 2017, Sebastian Riedel.
Licensed under the CC-SA License, Version 4.0, <http://creativecommons.org/licenses/by-sa/4.0>.
πΈ Bootstrap
Copyright (C) 2011-2021 The Bootstrap Authors.
Licensed under the MIT License, <http://creativecommons.org/licenses/MIT>.
πΈ jQuery
Copyright (C) jQuery Foundation.
Licensed under the MIT License, <http://creativecommons.org/licenses/MIT>.
πΈ D3.js
Copyright (C) 2010-2016, Michael Bostock.
Licensed under the 3-Clause BSD License, <https://opensource.org/licenses/BSD-3-Clause>.
πΈ epoch.js
Copyright (C) 2014 Fastly, Inc.
Licensed under the MIT License, <http://creativecommons.org/licenses/MIT>.
πΈ Font Awesome
Copyright (C) Dave Gandy.
Licensed under the MIT License, <http://creativecommons.org/licenses/MIT>, and the SIL OFL 1.1, <http://scripts.sil.org/OFL>.
πΈ moment.js
Copyright (C) JS Foundation and other contributors.
Licensed under the MIT License, <http://creativecommons.org/licenses/MIT>.
π AUTHORS π
the literal founders and the whole squad that made this happen:
π Project Founder
Sebastian Riedel, "sri@cpan.org".
π Contributors
In alphabetical order, no favourites, we love all of them equally:
- Andrey Khozov
- Andrii Nikitin
- Brian Medley
- Franz Skale
- Henrik Andersen
- Hubert
"depesz"Lubaczewski - Joel Berger
- Paul Williams
- Russell Shingleton
- Stefan Adams
- Stuart Skelton
π COPYRIGHT AND LICENSE π
Copyright (C) 2014-2024, Sebastian Riedel and others.
This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0. periodt. β¨
π SEE ALSO π
- <https://github.com/mojolicious/minion>
Minion::Guide- <https://minion.pm>
Mojolicious::Guides- <https://mojolicious.org>
and that's a wrap on the whole page, bestie π«Ά this one's rendered by perl v5.42.0 and dated 2026-01-17, filed under Minion(3). go forth and slay your job queues πβ¨
π¦ where this page comes from
- fedora 44: perl-Minion 11.0-2.fc44 Β· Artistic-2.0 AND CC-BY-SA-4.0 AND MIT AND ISC
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms