2

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();

3 Answers 3

1

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();
2
  • And what does it execute? Nothing it seems. Commented Oct 22, 2015 at 13:02
  • This code insert line into cron_schedule table Commented Oct 22, 2015 at 13:05
0

Try this

$timecreated   = strftime("%Y-%m-%d %H:%M:%S",  mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y")));
$timescheduled = strftime("%Y-%m-%d %H:%M:%S", mktime(date("H"), date("i")+ 5, date("s"), date("m"), date("d"), date("Y")));
$jobCode = 'job_id';

try {
    $schedule = Mage::getModel('cron/schedule');
     $schedule->setJobCode($jobCode)
        ->setCreatedAt($timecreated)
        ->setScheduledAt($timescheduled)
        ->setStatus(Mage_Cron_Model_Schedule::STATUS_PENDING)
        ->save();
   } catch (Exception $e) {
     throw new Exception(Mage::helper('cron')->__('Unable to save Cron expression'));
   }

Also check More Details...

0

Like you said, you also need a run model defined otherwise Magento just skips the entry. I am just having the same problem, here is what you need additionaly to the one you already have.

Mage::getModel('core/config_data')
        ->load('crontab/jobs/JOBNAME/run/model', 'path')
        ->setValue('classhandle/class_name::run')
        ->setPath('crontab/jobs/JOBNAME/run/model')
        ->save();

Magento actually does something like this if you check class Mage_Backup_Model_Config_Backend_Cron.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.