Magento 2 Cron Job In Custom Moudle

1. Create a class to run cron

  1. <?php
  2. namespace Magento\SampleMinimal\Cron;
  3. use \Psr\Log\LoggerInterface;
  4. class Test {
  5. protected $logger;
  6. public function __construct(LoggerInterface $logger) {
  7. $this->logger = $logger;
  8. }
  9. /**
  10. * Write to system.log
  11. *
  12. * @return void
  13. */
  14. public function execute() {
  15. $this->logger->info('Cron Works');
  16. }
  17. }

2. Create crontab.xml

  1. <?xml version="1.0"?>
  2. <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
  3. <group id="default">
  4. <job name="custom_cronjob" instance="Magento\SampleMinimal\Cron\Test" method="execute">
  5. <schedule>* * * * *</schedule>
  6. </job>
  7. </group>
  8. </config>

The preceding crontab.xml runs the Magento/SampleMinimal/Cron/Test.php class once per minute, resulting in a row being added to the cron_schedule table.

3. Verify the cron job

  1. php bin/magento cron:run

Reference Link: Configure a custom cron job and cron group (tutorial)