Programmatically: How to implement custom Magento cron jobs
Step 1: Create a new PHP file
Create a new file in the app/code/local/Company/Module/Cron directory (replace Company and Module with your module's namespace and name). Name the file Cron.php. Cron.php
class Company_Module_Cron_Cron
{
public function execute()
{
// Your custom cron job code goes here
echo "Custom Cron Job executed!";
}
}
Step 2: Register the cron job
In the same Cron.php file, register the cron job using the Mage::app()->getCache()->cleanType('cron'); method:
class Company_Module_Cron_Cron
{
public function execute()
{
// Your custom cron job code goes here
echo "Custom Cron Job executed!";
}
public static function register()
{
$cron = Mage::app()->getCache()->cleanType('cron');
$cron->addNewJob('Company_Module_Cron', 'execute', '0 0 * * *'); // Run every day at 12:00 AM
}
}
Step 3: Enable the cron job
To enable the cron job, go to the Magento admin panel, navigate to System > Configuration > Advanced > System > Cron Jobs, and click on "Add New Cron Job". Fill in the form with the following details: Job name: Enter a name for your cron job (e.g., "Custom Cron Job"). Job code: Enter Company_Module_Cron. Class method: Enter execute. Cron expression: Enter 0 0 * * * (or modify it as needed). Status: Set to "Enabled".
Click "Save" to save the changes.
Step 4: Run the cron job manually
To test your custom cron job, you can run it manually by going to the Magento admin panel, navigating to System > Cron Jobs, and clicking on "Run" next to your custom cron job.
How it works When you run the cron job manually or when it's scheduled to run automatically, Magento will execute the execute() method in your Cron.php file. This method contains your custom code that will be executed.