Created
October 24, 2016 04:08
-
-
Save brianmed/7668ff472f2cc7c6831227d3b5292b5e to your computer and use it in GitHub Desktop.
Mojolicious::Lite and Minion example for retrying jobs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Mojolicious::Lite; | |
app->log->level("debug"); | |
plugin Minion => { SQLite => 'sqlite:resources.db' }; | |
helper sql => sub { state $sql = Mojo::SQLite->new('sqlite:resources.db') }; | |
app->minion->add_task(run => sub { | |
my ($job, @args) = @_; | |
my $sql = $job->app->sql; | |
my $db = $sql->db; | |
$db->dbh->sqlite_busy_timeout(30_000); | |
my $tx = $db->begin; | |
my $mb_left = $db->query('select mb_left from settings')->hash->{mb_left}; | |
if ($mb_left < $args[0]) { | |
undef($tx); | |
$job->app->log->info("Retrying job $args[0]: $mb_left"); | |
$job->finish; | |
$job->retry({delay => 4}); | |
return; | |
} | |
$job->app->log->info("Running job $args[0]: $mb_left"); | |
$db->query('update settings set mb_left = mb_left - ?', $args[0]); | |
$tx->commit; | |
sleep(45); | |
$job->app->log->info("Finishing job $args[0]: $mb_left"); | |
$tx = $db->begin; | |
$db->query('update settings set mb_left = mb_left + ?', $args[0]); | |
$tx->commit; | |
$job->finish; | |
}); | |
app->start; | |
package Mojolicious::Command::run; | |
use Mojo::Base 'Mojolicious::Command'; | |
has description => 'Run commands'; | |
has usage => "Usage: APPLICATION run_commands\n"; | |
sub run { | |
my ($self, @args) = @_; | |
$self->app->minion->enqueue(run => [$args[0]]); | |
} | |
package Mojolicious::Command::migrate; | |
use Mojo::Base 'Mojolicious::Command'; | |
has description => 'Migrate db'; | |
has usage => "Usage: APPLICATION migrate\n"; | |
sub run { | |
my ($self, @args) = @_; | |
my $app = $self->app; | |
$app->sql->migrations->from_string($self->migration_string)->migrate; | |
$app->sql->db->query("INSERT INTO settings VALUES (1, 20)"); | |
} | |
sub migration_string { | |
return qq( | |
-- 1 up | |
CREATE TABLE settings ( | |
id INTEGER PRIMARY KEY AUTOINCREMENT, | |
mb_left INTEGER | |
); | |
); | |
} | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment