Goal of this article is to find a way to add sort order for cron jobs in Magento.
We should do rewrite of Mage_Cron_Model_Resource_Schedule_Collection.
Add a code in config.xml of our module (Webinse_Sortcron):
<?xml version="1.0" encoding="UTF-8"?>
<config>
.
.
<global>
<models>
<cron_resource>
<rewrite>
<schedule_collection>
Webinse_Sortcron_Model_Resource_Cron_Schedule_Collection
</schedule_collection>
</rewrite>
</cron_resource>
</models>
</global>
.
.
</config>
Create a file Webinse/Sortcron/Model/Resource/Cron/Schedule/Collection.php.
<?php class Webinse_Sortcron_Model_Resource_Cron_Schedule_Collection extends Mage_Cron_Model_Resource_Schedule_Collection {}
Here we should override the method:
public function getIterator()
{
$this->load();
$cron_jobs = $this->_items;
foreach ($cron_jobs as $job) {
if ($job->getJobCode() == 'job_code') {
$job->setSortOrder(1);
} else {
$job->setSortOrder(0);
}
}
return uasort($cron_jobs, array($this, 'sortJobs')) ? new ArrayIterator($cron_jobs) : new Array Iterator($this->_items);
}
public function sortJobs($a, $b)
{
if ($a->getSortOrder() == $b->getSortOrder()) {
return 0;
}
return ($b->getSortOrder() < $a->getSortOrder()) ? -1 : 1;
}
In the line 6 we set the highest priority to our task ('job_code'). In line 12 we should sort in descending order and it returns the resulting array. In line 15 you can see a sorting function.
Once that's such a small fixes we have an opportunity to add sort order for cron jobs in Magento. Now they will be executed in the order in which we need.
Enter a Comment