Site icon MageComp Blog

How To Get Last Executed Cron List Programmatically in Magento 2

How To Get Last Executed Cron List Programmatically in Magento 2

Hello Magento Friends ?,

The week begins and so programming! Today let us know How To Get Last Executed Cron List Programmatically in Magento 2. Before beginning, take a peek at the previously released article, How to cancel order Programmatically without disabling URL security key in Magento 2?.

Introduction:

Cron is one of the most astonishing features of Magento 2. Whenever there is any need to schedule tasks, at that time cron is used. Cron helps Magento store owners to execute commands at the given date and time. Cron jobs allow scheduling tasks, reindexing, generating emails, generating newsletters, and much more.

With regards to development reasons, or for analysis or for record purposes, there is a need to figure out the last executed cron list in Magento 2. Let us know How To Get Last Executed Cron List Programmatically in Magento 2 ?

Steps To Get Last Executed Cron List Programmatically in Magento 2:

Create the Block file at the following path:

app\code\Vendor\Extension\Block\cronlist.php

Now, add the below code.

<?php
namespace Vendor\Extension\Block;

class Info extends \Magento\Config\Block\System\Config\Form\Fieldset
{
    public function __construct(
        \Magento\Backend\Block\Context $context,
        \Magento\Cron\Model\ResourceModel\Schedule\CollectionFactory $cronFactory,
        array $data = [])
    {
        parent::__construct($context, $data);
        $this->cronFactory = $cronFactory;
    }
    /**
    *
     * @return string
     */
    private function getCronList()
    {
        $crontabCollection = $this->cronFactory->create();
        $crontabCollection->setOrder('schedule_id')->setPageSize(10);
        $value = '';
        if ($crontabCollection->count() > 0)
        {

            foreach ($crontabCollection as $crontabRow)
            {
                $value .=
                    '<div>'.
                    '<span>' . $crontabRow['status'] . '</span>' .
                    '<span>' . $crontabRow['job_code'] . '</span>' .
                    '<span>' . $crontabRow['created_at'] . '</span>' .
                    '</div>';
            }
        }
        return $value;
    }
}

That’s it!

Conclusion:

So, using the above code you can get the last 10 executed cron list in Magento 2. However, you can change the count as per your requirement.

You may also like to read How to Programmatically Check Particular Cron is Currently Running or not in Magento 2.

In case you face any difficulties while executing the above code, alert me by mentioning your issue in the comment part. Did you found the article useful? Hit the 5 stars and share it with your Magento friends. See you next time till then stay in the know!

Happy Coding ?

Exit mobile version