How to run cron job at a particular time in Magento 2?
-
14-04-2021 - |
سؤال
I want to create a cron job which update product price which are disabled and the cron run at a specific time 1 time in a day.
I have created a custom basic module from taking reference from https://www.mageplaza.com/devdocs/magento-2-create-cron-job/
My crontab.xml (path : app/code/Product/Cron/etc/crontab.xml )
<?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 instance="Product\Cron\Cron\Test" method="execute" name="mageplaza_helloworld_cron">
<schedule>*/1 * * * *</schedule>
</job>
</group>
</config>
my test.php is
<?php
namespace Cron\Run\Cron; (path : app/code/Product/Cron/Cron/Test.php )
class Test
{
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;
}
}
But it does't show me message in cron.log file. What am i missing any help is appreciated.
المحلول
Add This Files to your Custom Module and first check your module is enable or not. Your Module must be enable.
Create a class to run cron
app/code/VendoreName/ModuleName/Cron
Test.php
<?php
namespace VendoreName\ModuleName\Cron;
use Psr\Log\LoggerInterface;
class Test {
protected $logger;
public function __construct(LoggerInterface $logger) {
$this->logger = $logger;
}
public function execute() {
$this->logger->info('Cron Works');
}
}
Create crontab.xml
app/code/VendoreName/ModuleName/etc
crontab.xml
<?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="custom_cronjob" instance="VendoreName\ModuleName\Cron\Test" method="execute">
<schedule>* * * * *</schedule>
</job>
</group>
</config>
Compile and cache clean
bin/magento s:up
bin/magento setup:di:compile
bin/magento cache:clean
Verify the cron job
This step shows how to verify the custom cron job successfully using a SQL query on the cron_schedule database table.
- Run Magento cron jobs:
bin/magento cron:run
- Enter the magento cron:run command two or three times.
The first time you enter the command, it queues jobs; subsequently, the cron jobs are run. You must enter the command at least twice.
- Run the SQL query SELECT * from cron_schedule WHERE job_code like '%custom%'
- Verify messages are written to Magento’s system log:
var/www/html/magento_root/var/log/system.log
I Hope This Helps You.