How to Setup Custom Cron Job in Magento 2

Hello Everyone,

In this blog, we will learn about how to Setup Custom Cron Job in Magento 2.

What is Cron Job ?

Magento Cron Job runs automatically at specific time and date to perform some task like Send Email, reindexing, Send Newsletters, Currency Rate Change etc.

Without wasting your time, let us guide you straight away. Follow the easy step given below to Setup Custom Cron Job in Magento 2.

STEPS FOR SETUP CUSTOM CRON JOB IN MAGENTO 2

Step 1: Create crontab.xml file

app/code/Vendor/Extension/etc/crontab.xml

<?xml version="1.0" ?>
<config>
    <group id="default">
        <job name="magecurious_cron" instance="Vendor\Extension\Cron\CustomCron" method="execute">
            <schedule>* * * * *</schedule>
        </job>
    </group>
</config>

See the Explanation of Schedule Time * * * * *

  • – Day of the Week (0 – 6)
  • – Month (1 – 12)
  • – Day of Month (1 – 31)
  • – Hour (0 – 23)
  • – Minute (0 – 59)

You can customize this time according to your requirement.

Step 2: Create Custom Cron.php file

app/code/Vendor/Extension/Cron/CustomCron.php

<?php

namespace Vendor\Extension\Cron;

class CustomCron
{
    protected $logger;

    /**
    * Constructor
    *
    * @param \Psr\Log\LoggerInterface $logger
    */
    public function __construct(\Psr\Log\LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function execute()
    {   
        $this->logger->info("Magecurious custom cron is executed.");
        //add your custom cron job logic here.
    }
}

Here we add log but you can define your own custom logic like send email, send newsletter etc.

Step 3: Finally run the below commands.

$ php bin/magento setup:upgrade
$ php bin/magento cache:clean
$ php bin/magento cache:flush
$ php bin/magento cron:run;

List of Useful Cron Related Commands:

php bin/magento cron:install
crontab -l
php bin/magento cron:run
php bin/magento cron:remove

Final Thoughts:

So this was the easiest way which we have told you in this blog. This is how you can Setup Custom Cron Job in Magento 2. Hope you liked the blog.

So quickly go to the comment box and tell me how you like this blog?

Stay tuned with us on our site to get new updates of Magento.

Thanks for reading and visiting our site.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Leave a Reply

Your email address will not be published. Required fields are marked *