Magento 2 Cron job: Everything you need to know

The cron job is a great feature of Linux, the free operating system for the user. The cron job will create a command or a script that is appropriate to the task you want to do. Instead of manual working, the cronjob allows running automatically at the exact time and date. Due to its automation, then cron jobs are the perfect choice for repeated projects every date or every week. Cron configuration is very important in Magento to set the schedule for many system activities such as reindexing, auto-update of currency rates, Magento emails, etc. Only when the Magento 2 Cron job configuration is correct, the cron job is active. In the case of making an error, this means Magento won’t function as expected.

Why need Magento 2 Cron Job

magento-2-cron-job

Several Magento features require at least one Magento 2 Cron Job, which schedules activities to occur in the future. A partial list of these activities follows:

  • Catalog price rules
  • Newsletters
  • Generating Google sitemaps
  • Customer Alerts/Notifications (product price change, product back in stock)
  • Reindexing
  • Private sales (Magento Commerce only)>
  • Automatic updating of currency rates
  • All Magento emails (including order confirmation and transactional)

Run and Create Magento 2 cron job

Please follow the guides to start the cron job program as your wish while the cron schedule is set by you.

  • Create a class within the “Cron” folder
  • Manually setup the cron schedule by using PHP: bin/magento cron:run
  • Find a log in the var/log/system.log after the cronjob has run.
  • Login to Magento 2 Admin panel, do as the path: Stores > Configuration > Advanced > System, then change scheduler settings per cron group.
  • Finally, run cron from the command line:

magento cron:run [–group=”<cron group name>”]

1. Create crontab.xml

File: app/code/MGS/Sample/etc/crontab.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
        <group id="default">
                <job instance="MGS\Sample\Cron\TestCron" method="execute" name="mgs_sample_cron">
                         <schedule>* * * * *</schedule>
                 </job>
        </group>
</config>


  • group id is your cron group name. You can run only cron for a single group at a time.
  • job instance is class to be instantiated (classpath).
  • job method is a method in job instance to call.
  • job name is Unique ID for this cron job.
  • schedule is scheduled in cron format. The following graph shows what it consists of:
* * * * * command to be executed
| | | | |
| | | | +----- Day of week (0 - 7) (Sunday=0 or 7)
| | | +------- Month (1 - 12)
| | +--------- Day of month (1 - 31)
| +----------- Hour (0 - 23)
+------------- Minute (0 - 59)

2. Create Test.php

File: app/code/MGS/Sample/Cron/TestCron.php

<?php
namespace MGS\Sample\Cron;
class TestCron
{
       public function execute()
       {
         $test = new \Zend\Log\Writer\Stream(BP . '/var/log/cron.log');
         $logger = new \Zend\Log\Logger();
         $logger->addWriter($test);
         $logger->info(__METHOD__);
          return $this;
        }
}

All done, please flush cache and run Magento cron: run –group=”default” from the command line

How to determine cron not working?

magento-2-cron-job

a) To install Magento 2 Cron Scheduler extension

Nowadays, there are many extensions that perform complex checking and visualization of cron task performance. You can easily find them with the inquiry “Magento 2 cron job scheduler extension” or “Magento 2 cron module”

b) To check directly in the database 

In case you do not want to install an additional extension, it is enough for you to open up DB (via phpMyAdmin, for example) and run a simple SQL query:

SELECT MAX(executed_at) FROM cron_schedule

If cron works correctly, you get almost the current time (max 5 min deviation)

Another useful SQL query that returns the list of log errors:

SELECT job_code, messages FROM cron_schedule WHERE messages IS NOT NULL

Magento 2 Cron job is not working. What should I do?

In Magento 2 cron job performance is related to the command bin/magento cron:run

Connect via ssh and run the command crontab -l to obtain the list of active cronjobs. After your run the command crontab -l > crontab.cfg you will record the current configuration to a file for the following editing. The command and vice versa install the configuration from the file.

Also, you can set up cron via Cpanel, the same configurations, however, via a web interface (Cpanel > Cron Jobs or Cpanel > Scheduled Tasks)

If you already have cronjob or you only have to add it, we recommend using the following command:

* * * * * php -f [store root]/bin/magento cron:run >> [store root]/var/log/magento.cron.log 2>&1;

where [store root] is the root directory with installed Magento.

This command is slightly different from a command given in Magento 2 manuals. However, it brings a variety of unquestionable advantages: ANY error and any successful performance will be recorded in a log file.

After the new Magento 2 cron job configuring, within the next minute, the log file store [root]/var/log/magento.cron.log with the error text or successful performance notification “Ran jobs by schedule.” will appear.

If the file does not occur within the next 1 minute, it means the wrong path to the root directory or no permissions to write to the directory var/log/

Conclusion

Magento 2 Cron job is essentially important. That is why you should pay so much attention to it and be sure that it operates correctly. Through this post, we hope you can be able to grasp how to use Cron job in Magento 2. If you utilize this feature with just some simple movements, hiring a qualified Magento Website Development service will be a good choice. We not only offer an affordable solution for all sizes and budgets but also ensure that it helps your online business grow and sustain itself. Contact us for a free consultation!

Magento 2.4.4: What latest features, upgrades, and enhancement