How To Run Periodic Code in Magento 1

Time to Read: Difficulty Level: Beginner
Tools Needed: Magento installation, ability to edit files via FTP or Plesk File Manager Last Updated: 07/12/2018

Periodic code and crons

If you wish to run a piece of code periodically, for example every hour, or at midnight every day, the best way to do this is to put it in a cron task.

Magento 1 manages its own cron tasks using the internal crontab functionality. This queues up all the Magento code that wishes to be automatically run without user intervention.

This feature allows you to safely and easily create your own extension and lets you add your own tasks to Magento’s cron functionality.

Method

Method

All it needs is 3 simple files.

You will need to create the folder structures to accommodate the files.

/app/code/local/Mycompany/Myextension/etc/config.xml




0.1.0





Mycompany_Myextension_Model






*/30 * * * *
myextension/myextension::cron



​Note the following line in particular:

*/30 * * * *

​This sets the frequency at which your cron task will execute, and is currently set to every 30 minutes. For more information on CRON expressions see here.

/app/etc/modules/Mycompany_Myextension.xml

<?xml version="1.0"?>



true
local


/app/code/local/Mycompany/ Myextension/Model/Myextension.php

<?php
class Mycompany_Myextension_Model_Myextension extends Mage_Core_Model_Abstract {
public function _construct() {
parent::_construct();
$this->_init('myextension/myextension');
}
public function cron(){
// Your code goes here!
}
}

And that’s it!

Simply put your PHP code into the cron() method and it should run as frequently as you’ve specify in config.xml.

If for some reason your code doesn’t run, check your system and/or exception log files for possible code errors, and check that your hosting solution has a cron setup to run Magento’s cron.php.

Additionally, check that the correct case is used in file and folder names and in the xml and php files for the extension and module names.