Categories: How ToMagento 2

How to Programmatically Check Particular Cron is Currently Running or not in Magento 2

One of the most stunning features of Magento 2 is cron job that enables you to execute repetitive task periodically without any efforts. You can use this cron job to run various scheduled tasks, like.

  • Re-indexing
  • Catalog price rules
  • Sending newsletters
  • Generating Google Sitemaps
  • Customer notifications or alert messages
  • Auto update currency rates
  • Scheduled database logs cleanups
  • Cache cleanups
  • Generating site maps and more.

With just a date and time you are done with setting up cron. After that, the Magento cronjob manager will list all cron jobs and run it sequentially. When there is a number of cron jobs listed, you don’t know which job is currently in progress. Because of that, sometimes it happens when there is less time between executions of crons, it may create conflictions with one another. That’s the reason we always recommend you to check that particular cron is executed or not?
So, we are back with a super exciting blog that will help you to know which cron job is currently running on your Magento 2 Server using this small piece of code.
In the first step, we need to create a cron using “crontab.xml” file at the following location.
app\code\Vendor\Extension\etc\crontab.xml

<pre class="lang:default decode:true"><!--?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 name="reviewreminder_cron" instance="Magecomp\Reviewreminder\Cron\Reviewcron" method="execute">
            <schedule> */5 * * * *</schedule>
        </job>
    </group>
</config>
</pre>

Now, in second step, we need to create one more file named “Mycronfile.php” at this path.
app\code\Vendor\Extension\Cron\Mycronfile.php

<pre class="lang:default decode:true"><!--?php namespace Vendor\Extension\Cron; class Mycronfile { public $logger; public $cronCollection; public function __construct( \Psr\Log\LoggerInterface $logger, \Vendor\Extension\Model\ResourceModel\Cron\CollectionFactory $cronCollection, ) { $this-&gt;logger = $logger;
             $this-&gt;cronCollection  = $cronCollection;
}
public function execute()
{
    try
    {
        if ($this-&gt;isCronrunning(‘vendor_extension_cronname')) {
            $this-&gt;logger-&gt;critical('vendor_extension_cronname Job Run');
            return;
        }
        //Do YOUR FURTHER LOGIC HERE
    }
    catch (\Exception $e)
    {
           $this-&gt;logger-&gt;critical($e-&gt;getMessage());
    }
}
public function isCronrunning($croncode)
{
 $currentRunningJob = $this-&gt;cronCollection-&gt;create()
        -&gt;addFieldToFilter('job_code', $croncode)
        -&gt;addFieldToFilter('status', 'running')
     -&gt;setPageSize(1);
 
 if ($currentRunningJob-&gt;getSize()) {
     $jobScheduledAtDate =  $this-&gt;cronCollection-&gt;create()
            -&gt;addFieldToFilter('job_code', $jobCode)
            -&gt;addFieldToFilter('scheduled_at', $currentRunningJob-&gt;getFirstItem()-&gt;getScheduledAt())
            -&gt;addFieldToFilter('status', ['in' =&gt; ['success', 'failed']]);
 
     return ($jobScheduledAtDate-&gt;getSize()) ? true : false;
 }
 return false;
}
}
</pre>

In this third and last step we need to create cron collection file at this path. app\code\Vendor\Extesnion\Model\ResourceModel\Cron\Collection.php

<pre class="lang:default decode:true">
<!--?php namespace Vendor\Extension\Model\ResourceModel\Cron; 
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection { protected $_idFieldName = 'schedule_id'; public function _construct() { $this->_init(\Magento\Cron\Model\Schedule::class, \Magento\Cron\Model\ResourceModel\Schedule::class);
   }
 } 
</pre>

That’s it for today, Let us know if you are facing an issue while implementing using this code by commenting below.

Happy Croning!

Click to rate this post!
[Total: 8 Average: 3.5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

  • Incomplete blog about file
    app\code\Vendor\Extesnion\Model\ResourceModel\Cron\Collection.php

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

2 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

4 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

4 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

5 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

6 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago