Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/sprout/Controllers/CronJobController.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use Kohana;
use Sprout\Controllers\Admin\ManagedAdminController;
use Sprout\Helpers\Mutex;
use Sprout\Helpers\Register;
use Sprout\Helpers\Sprout;

Expand Down Expand Up @@ -52,6 +53,13 @@ public function run($schedule)
exit(1);
}

$mutex = Mutex::create('cron_job:' . $schedule);

if (!$mutex->acquire()) {
fwrite(STDERR, "Cron schedule [{$schedule}] already running" . PHP_EOL);
exit(0);
}

$jobs = Register::getCronJobs($schedule);
echo 'Num jobs: ', count($jobs), PHP_EOL;

Expand Down Expand Up @@ -102,6 +110,8 @@ public function run($schedule)
}
}

$mutex->release();

echo PHP_EOL, 'Failures: ', $failed, PHP_EOL;
exit($failed);
}
Expand Down
59 changes: 59 additions & 0 deletions src/sprout/Helpers/Mutex.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php
/*
* Copyright (C) 2025 Karmabunny Pty Ltd.
*
* This file is a part of SproutCMS.
*
* SproutCMS is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, either
* version 2 of the License, or (at your option) any later version.
*
* For more information, visit <http://getsproutcms.com>.
*/
namespace Sprout\Helpers;

use karmabunny\interfaces\MutexInterface;
use karmabunny\pdb\PdbMutex;
use karmabunny\rdb\RdbMutex;
use Kohana;
use Kohana_Exception;

/**
* Mutex helper.
*/
class Mutex
{

/**
* Create a new mutex.
*
* @param string $name mutex name
* @param string $group config group
* @return MutexInterface
* @throws Kohana_Exception
*/
public static function create(string $name, string $group = 'default'): MutexInterface
{
$config = Kohana::config('mutex.' . $group);

if ($config['driver'] === 'pdb') {
$pdb = Pdb::getInstance();
$mutex = new PdbMutex($pdb, $name);

} else if ($config['driver'] === 'redis') {
$rdb = Rdb::getInstance();
$mutex = new RdbMutex($rdb, $name);

} else {
throw new Kohana_Exception('Unknown mutex driver: ' . $config['driver']);
}

foreach ($config['config'] as $key => $value) {
if (property_exists($mutex, $key)) {
$mutex->$key = $value;
}
}

return $mutex;
}
}
17 changes: 17 additions & 0 deletions src/sprout/config/mutex.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

$config['default'] = [
'driver' => 'pdb',
'config' => [
'autoRelease' => true,
'uniqueLocks' => true,
'releaseAllLocks' => false,
],

// 'driver' => 'redis',
// 'config' => [
// 'autoRelease' => true,
// 'prefix' => 'mutex:',
// 'autoExpire' => 60,
// ],
];