Magento 2 is loaded with many awesome features, and Cron Job is one of the most useful among them. Cron is a time-based scheduler and it is useful to run commands automatically with scheduled time and date in Magento 2.
Why Configure Magento 2 Cron Job?
Cron is one the most important part of Magento 2. You can schedule multiple activities via cron which are listed below:
- Generating Google sitemaps
- Catalog price rules
- Customer Alerts and Notifications.
- Private sales (Magento Enterprise Edition only)
- All Magento e-mails which also includes order confirmation and transactional.
- Auto update currency rates
For more details, you may check the official documentation on Cron Job.
How to Configure Magento 2 Cron Job?
Today, I am going to guide you how to setup Cron Job in Magento using a custom module. I hope that you already have created a custom module in Magento 2. So, let’s start!
Create crontab.xml file in app/code/Magenticians/Mymodule/etc and paste the following code in it:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
<job name="cron_name" instance="Magenticians\Mymodule\Cron\Run" method="execute">
<schedule>*/1 * * * *</schedule>-->
In the code above, I have scheduled it for one minute. I have set the group id default and job name as cron_name, and you can change them if you want.
First, create directory Cron in your custom module so, the directory will now look like this: app/code/Magenticians/Mymodule/Cron. Now create Run.php file in app/code/Magenticians/Mymodule/Cron and paste the following code in it:
public function __construct(
$this->_logger = $logger;
public function execute()
//Edit it according to your requirement
$this->_logger->debug('Cron run successfully');
Run Magento 2 Cron Job
Connect your store with an SSH and go to the root directory of your Magento 2. Now run these commands:
php bin/magento cache:flush
php bin/magento cron:run
You can also run Cron job for one group only by running this command:
php bin/magento cron:run --group="your_group_name"
To check whether the Cron is working properly, go to var/log/debug.log of your store and you will see the text Cron run successfully in it. Go to cron_schedule table of database and you will see a new entry in it with your Cron job name.
Cron job is very important for Magento 2 store through which you can save your time by scheduling and automating its activities. After following this guide, I hope you are now capable to easily setup Cron Job in Magento 2. If you still have any issues or want to discuss something related to Magento 2 Cron Job, feel free to use the comment box below!
Subscribe to get latest Magento news