Magento – How to execute cron jobs automatically every week in magento 2 custom module

crontabmagento-cronmagento2

I have created crontab.xml in vendor/module/etc directory

<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="get_carriers" instance="Vendor\Module\Cron\GetCarriers" method="execute">
        <schedule>* * * * *</schedule>
    </job>
</group>

And create GetCarriers.php in Vendor/Module/Cron/GetCarriers.php

namespace Vendor\Module\Cron;
     class GetCarriers {

     protected $_logger;

     public function __construct(\Psr\Log\LoggerInterface $logger) {
           $this->_logger = $logger;
     }

     public function execute() {
           $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/cron.log');
           $logger = new \Zend\Log\Logger();
           $logger->addWriter($writer);
           $logger->info(__METHOD__);

           return $this;
     }
}

Now if i execute php bin/magento cron:run –group="default" cron run but i want it to execute automatically every week.

Best Answer

Just change your crontab schedule as below

<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="get_carriers" instance="Vendor\Module\Cron\GetCarriers" method="execute">
           <schedule>0 0 * * 0</schedule>
       </job>
    </group>
</config>

Above schedule run the cron job for every Sunday at 00:00:00

0 0 * * 0 == Sunday 00:00:00
.
.
.
.
.
0 0 * * 6 == Saturday 00:00:00

Simmilarly you can adjust time, you can use the online cron formatter to adjust the settings and tested it immediately.

Note: I hope you already configure crontab, if not just run the below command to configure.

php bin/magento cron:install