From d7f2ed07de8684cf9e9c5a9dc9a168b48ba74ccd Mon Sep 17 00:00:00 2001 From: Nivanka Fonseka Date: Tue, 9 Nov 2021 15:56:55 +1300 Subject: [PATCH] added Queued Cron Task to define a priority order for the cron tasks --- src/Controllers/CronTaskController.php | 24 ++++++++++++++++++++---- src/Interfaces/QueuedCronTask.php | 18 ++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) create mode 100644 src/Interfaces/QueuedCronTask.php diff --git a/src/Controllers/CronTaskController.php b/src/Controllers/CronTaskController.php index d3c2985..952d768 100644 --- a/src/Controllers/CronTaskController.php +++ b/src/Controllers/CronTaskController.php @@ -13,6 +13,7 @@ use SilverStripe\Core\Injector\Injector; use SilverStripe\CronTask\CronTaskStatus; use SilverStripe\CronTask\Interfaces\CronTask; +use SilverStripe\CronTask\Interfaces\QueuedCronTask; use SilverStripe\ORM\FieldType\DBDatetime; use SilverStripe\Security\Permission; use SilverStripe\Security\Security; @@ -129,18 +130,33 @@ public function index(HTTPRequest $request) $isDebug = (bool)$request->getVar('debug'); // Check each task - $tasks = ClassInfo::implementorsOf(CronTask::class); + $tasks = array_merge( + ClassInfo::implementorsOf(CronTask::class), + ClassInfo::implementorsOf(QueuedCronTask::class), + ); if (empty($tasks)) { $this->output("There are no implementators of CronTask to run", 2); return; } + + $jobs = []; foreach ($tasks as $subclass) { - $task = Injector::inst()->create($subclass); + $jobs[] = Injector::inst()->create($subclass); + } + + usort($jobs, function ($a, $b) { + $priorityA = method_exists($a, 'priority') ? $a->priority() : 0; + $priorityB = method_exists($b, 'priority') ? $b->priority() : 0; + return $priorityA > $priorityB ? -1 : 1; + }); + + foreach ($jobs as $job) { // falsey schedule = don't run task - if ($task->getSchedule()) { - $this->runTask($task, $isDebug); + if ($job->getSchedule()) { + $this->runTask($job, $isDebug); } } + } /** diff --git a/src/Interfaces/QueuedCronTask.php b/src/Interfaces/QueuedCronTask.php new file mode 100644 index 0000000..c8a4671 --- /dev/null +++ b/src/Interfaces/QueuedCronTask.php @@ -0,0 +1,18 @@ +