Magento allows you to schedule custom tasks in an XML configuration, in a similar manner to the UNIX crontab style.
..... ... * * * 12 * mymodel/observer::runScheduledFunction
This example will run Ayasoftware_Mymodel_Model_Observer::runScheduledFunction method every December (* * * 12 *).
class Ayasoftware_Mymodel_Model_Observer extends Mage_Core_Model_Abstract { public function runScheduledFunction ($observer) { Mage::log("nice to learn this "); } }
Update the Magento cron_schedule table, If for a reason X, you want to run this function at a specified time for example at 2010-05-21 17:45:00 , without having to change the configuration above.
This php code creates a pending cron job (created at $timecreated and Scheduled at $timescheduled):
$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"))); try { $coreResource = Mage::getSingleton ( 'core/resource' ); $write = $coreResource->getConnection ( 'core_write' ); $cron_schedule = $coreResource->getTableName ( 'cron_schedule' ); // Delete pending or completed crons $write->query("DELETE FROM $cron_schedule WHERE job_code = 'job_id'"); $sql = "INSERT INTO $cron_schedule ( schedule_id , job_code , status , messages , created_at , scheduled_at , executed_at , finished_at ) VALUES ( NULL , 'job_id', 'pending', NULL, '$timecreated' , '$timescheduled', '0000-00-00 00:00:00', '0000-00-00 00:00:00' )"; $write->query($sql); } catch (Exception $e) { throw new Exception(Mage::helper('cron')->__('Unable to save This Cron Job')); }
If you want to use Magento core functions:
$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')); }
Dont forget to setup a cron ( for the file {{base_dir}}/cron.php) that runs every 5 (for example) minutes to check whether there is any pending task.
Let me know if you have any question.