Hello Magento Friends,
Cron jobs are scheduled tasks that automate repetitive processes in your Magento 2 store. These tasks, like sending emails, updating product inventory, or running indexers, are crucial for maintaining the store’s functionality and performance. By default, Magento 2 comes with a set of built-in cron jobs. However, there might be times when you need to disable a specific default cron job programmatically.
Contents
Reasons to Disable Default Cron Jobs
- Conflict with Custom Cron Jobs: If you’ve created custom cron jobs for specific tasks, they might conflict with default jobs, leading to unexpected behavior.
- Performance Optimization: Certain default cron jobs might not be necessary for your store’s current needs, and disabling them can improve performance.
- Debugging: Disabling specific cron jobs can help isolate issues and troubleshoot problems.
Steps to Disable Default Cron Job Programmatically in Magento 2:
Step 1: First, we need to create a “di.xml“ file inside our extension at the following path
app\code\Vendor\Extension\etc\di.xml
Now, add the code as follows
1 2 3 4 5 6 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Cron\Model\Config"> <plugin name="disable_default_cron_jobs" type="Vendor\Extension\Plugin\Disabledefaultcronjobs"/> </type> </config> |
Step 2: After that, we need to create a “Disabledefaultcronjobs.php” file inside our extension at the following path
app\code\Vendor\Extension\Plugin\Disabledefaultcronjobs.php
And add the code as given below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php namespace Vendor\Extension\Plugin; class Disabledefaultcronjobs { public function aroundGetJobs(\Magento\Cron\Model\Config $subject, callable $proceed) { // Get all configured jobs $jobs = $proceed(); // List of jobs to keep (your custom jobs) $allowedJobs = [ 'backend_clean_cache', // Replace with your custom job name ]; // Filter out Magento default jobs foreach ($jobs as $group => $groupJobs) { foreach ($groupJobs as $jobName => $jobConfig) { if (!in_array($jobName, $allowedJobs)) { unset($jobs[$group][$jobName]); } } } return $jobs; } } |
Note: All default Magento cron jobs are disabled except those specified in the $allowedJobs array.
Conclusion:
Disabling a default cron job in Magento 2 can be useful for optimizing your store’s performance or preventing conflicts with custom code or third-party extensions. Using a custom module and plugin ensures you avoid directly modifying core Magento files, keeping your store more maintainable and upgrade-safe.
By following the steps outlined in this tutorial, you can easily disable unnecessary cron jobs programmatically in Magento 2.
Happy Coding!