Minion - Job queue
use Minion; # Connect to backend my $minion = Minion->new(Pg => 'postgresql://postgres@/test'); # Add tasks $minion->add_task(something_slow => sub { my ($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; # Build more sophisticated workers my $worker = $minion->repair->worker; while (int rand 2) { if (my $job = $worker->register->dequeue(5)) { $job->perform } } $worker->unregister;
Minion is a job queue for the Mojolicious real-time web framework, with support for multiple named queues, priorities, delayed jobs, job dependencies, job progress, job results, retries with backoff, rate limiting, unique jobs, statistics, distributed workers, parallel processing, autoscaling, remote control, admin ui, resource leak protection and multiple backends (such as PostgreSQL).
Job queues allow you to process time and/or computationally intensive tasks in background processes, outside of the request/response lifecycle. 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.
use Mojolicious::Lite; plugin Minion => {Pg => 'postgresql://sri:s3cret@localhost/test'}; # Slow task app->minion->add_task(poke_mojo => sub { my $job = shift; $job->app->ua->get('mojolicious.org'); $job->app->log->debug('We have poked mojolicious.org for a visitor'); }); # Perform job in a background worker process get '/' => sub { my $c = shift; $c->minion->enqueue('poke_mojo'); $c->render(text => 'We will poke mojolicious.org for you soon.'); }; app->start;
Background worker processes are usually started with the command Minion::Command::minion::worker, which becomes automatically available when an application loads the plugin Mojolicious::Plugin::Minion.
$ ./myapp.pl minion worker
Jobs can be managed right from the command line with Minion::Command::minion::job.
$ ./myapp.pl minion job
You can also add an admin ui to your application by loading the plugin Mojolicious::Plugin::Minion::Admin. Just make sure to secure access before making your application publically accessible.
# Make admin ui available under "/minion" plugin 'Minion::Admin';
To manage background worker processes with systemd, you can use a unit configuration file like this.
[Unit] Description=My Mojolicious application workers After=postgresql.service [Service] Type=simple ExecStart=/home/sri/myapp/myapp.pl minion worker -m production KillMode=process [Install] WantedBy=multi-user.target
Every job can fail or succeed, but not get lost, the system is eventually consistent and will preserve job results for as long as you like, depending on "remove_after". While individual workers can fail in the middle of processing a job, the system will detect this and ensure that no job is left in an uncertain state, depending on "missing_after".
And as your application grows, you can move tasks into application specific plugins.
package MyApp::Task::PokeMojo; use Mojo::Base 'Mojolicious::Plugin'; sub register { my ($self, $app) = @_; $app->minion->add_task(poke_mojo => sub { my $job = shift; $job->app->ua->get('mojolicious.org'); $job->app->log->debug('We have poked mojolicious.org for a visitor'); }); } 1;
Which are loaded like any other plugin from your application.
# Mojolicious $app->plugin('MyApp::Task::PokeMojo'); # Mojolicious::Lite plugin 'MyApp::Task::PokeMojo';
This distribution also contains a great example application you can use for inspiration. The link checker will show you how to integrate background jobs into well-structured Mojolicious applications.
Minion inherits all events from Mojo::EventEmitter and can emit the following new ones.
$minion->on(enqueue => sub { my ($minion, $id) = @_; ... });
Emitted after a job has been enqueued, in the process that enqueued it.
$minion->on(enqueue => sub { my ($minion, $id) = @_; say "Job $id has been enqueued."; });
$minion->on(worker => sub { my ($minion, $worker) = @_; ... });
Emitted in the worker process after it has been created.
$minion->on(worker => sub { my ($minion, $worker) = @_; my $id = $worker->id; say "Worker $$:$id started."; });
Minion implements the following attributes.
my $app = $minion->app; $minion = $minion->app(MyApp->new);
Application for job queue, defaults to a Mojo::HelloWorld object.
my $backend = $minion->backend; $minion = $minion->backend(Minion::Backend::Pg->new);
Backend, usually a Minion::Backend::Pg object.
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.
(retries ** 4) + 15
25
21
$minion->backoff(sub { my $retries = shift; return ($retries ** 4) + 15 + int(rand 30); });
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).
1800
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).
finished
172800
my $tasks = $minion->tasks; $minion = $minion->tasks({foo => sub {...}});
Registered tasks.
Minion inherits all methods from Mojo::EventEmitter and implements the following new ones.
$minion = $minion->add_task(foo => sub {...});
Register a task.
# Job with result $minion->add_task(add => sub { my ($job, $first, $second) = @_; $job->finish($first + $second); }); my $id = $minion->enqueue(add => [1, 1]); my $result = $minion->job($id)->info->{result};
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.
inactive
These options are currently available:
attempts => 25
Number of times performing this job will be attempted, with a delay based on "backoff" after the first attempt, defaults to 1.
1
delay => 10
Delay job for this many seconds (from now), defaults to 0.
0
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.
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.
priority => 5
Job priority, defaults to 0. Jobs with a higher priority get performed first.
queue => 'important'
Queue to put job in, defaults to default.
default
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.
minion_foreground
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.
undef
# Only one job should run at a time (unique job) $minion->add_task(do_unique_stuff => sub { my ($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 { my ($job, @args) = @_; return $job->retry({delay => 30}) unless my $guard = $minion->guard('some_web_service', 60, {limit => 5}); ... });
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.
# 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};
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 { my ($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 { my ($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 { my ($job, @args) = @_; return $job->retry({delay => 3600}) unless $minion->lock('another_web_service', 3600, {limit => 100}); ... });
limit => 20
Number of shared locks with the same name that can be active at the same time, defaults to 1.
my $minion = Minion->new(Pg => 'postgresql://postgres@/test'); my $minion = Minion->new(Pg => Mojo::Pg->new);
Construct a new Minion object.
$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;
queues => ['important']
One or more queues to dequeue jobs from, defaults to default.
$minion = $minion->repair;
Repair worker registry and job queue if necessary.
$minion = $minion->reset;
Reset job queue.
my $stats = $minion->stats;
Get statistics for jobs and workers.
# Check idle workers my $idle = $minion->stats->{inactive_workers};
These fields are currently available:
active_jobs => 100
Number of jobs in active state.
active
active_workers => 100
Number of workers that are currently processing a job.
delayed_jobs => 100
Number of jobs in inactive state that are scheduled to run at specific time in the future or have unresolved dependencies. Note that this field is EXPERIMENTAL and might change without warning!
enqueued_jobs => 100000
Rough estimate of how many jobs have ever been enqueued. Note that this field is EXPERIMENTAL and might change without warning!
failed_jobs => 100
Number of jobs in failed state.
failed
finished_jobs => 100
Number of jobs in finished state.
inactive_jobs => 100
Number of jobs in inactive state.
inactive_workers => 100
Number of workers that are currently not processing a job.
uptime => 1000
Uptime in seconds.
my $bool = $minion->unlock('foo');
Release a named lock that has been previously acquired with "lock".
my $worker = $minion->worker;
Build Minion::Worker object.
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::Job
Minion::Worker
Mojolicious::Plugin::Minion
Mojolicious::Plugin::Minion::Admin
The Minion distribution includes a few files with different licenses that have been bundled for internal use.
Copyright (C) 2017, Sebastian Riedel.
Licensed under the CC-SA License, Version 4.0 http://creativecommons.org/licenses/by-sa/4.0.
Copyright (C) 2011-2016 Twitter, Inc.
Licensed under the MIT License, http://creativecommons.org/licenses/MIT.
Copyright (C) 2010-2016, Michael Bostock.
Licensed under the 3-Clause BSD License, https://opensource.org/licenses/BSD-3-Clause.
Copyright (C) 2014 Fastly, Inc.
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.
Copyright (C) JS Foundation and other contributors.
Sebastian Riedel, sri@cpan.org.
sri@cpan.org
In alphabetical order:
Andrey Khozov
Brian Medley
Hubert "depesz" Lubaczewski
Joel Berger
Paul Williams
Copyright (C) 2014-2017, 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.
https://github.com/kraih/minion, Mojolicious::Guides, http://mojolicious.org.
To install Minion, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Minion
CPAN shell
perl -MCPAN -e shell install Minion
For more information on module installation, please visit the detailed CPAN module installation guide.