Magento – How to create a cron job programatically

croncrontabmagento-1.9module

How can I create a cron job in Magento without defining <run><model></model></run> in the XML?

I have a lot of jobs that need to be changed programmatically and we couldn't define all of these jobs in the XML as these need to be dynamic.

So far, this insert the job in the magento cron, however, there's no run/model defined:

Mage::getModel('core/config_data')
                ->load(self::CRON_STRING_PATH, 'path')
                ->setValue($cronExprString)
                ->setPath(self::CRON_STRING_PATH)
                ->save();

Best Answer

This code inserts the cron job into cron_schedule table:

$job_code='my_great_job_code';
/* */
$time = time(); // or time()+60 if you want...
$date = strftime('%Y-%m-%d %H:%M:00', $time);
/* */
$schedule = Mage::getModel('cron/schedule');
$schedule->setCreatedAt(strftime('%Y-%m-%d %H:%M:00', time()));
$schedule->setScheduledAt($date);
$schedule->setStatus(Mage_Cron_Model_Schedule::STATUS_PENDING);
$schedule->setJobCode($job_code);
$schedule->save();
Related Topic