Today we learn how to Create Cron Job Programmatically in Magento 2
What is Cron Job in Magento 2?
Cron Job is most essential feature to allow you to automate certain commands or scripts on your server to complete repetitive tasks automatically. This is normally used to schedule a job that is executed periodically.
In Magento 2 There are some common cron are below
- Generating Google sitemaps
- Newsletters
- Catalog price rules
- Customer Alerts/Notifications (product price change, product back in stock)
- Reindexing
- Automatic updating of currency rates
- All Magento e-mails (including order confirmation and transactional)
Here are some commands below
Install cron
bin/magento cron:install [–force]
Use –force to rewrite an existing Magento crontab.
To view the crontab
crontab -l
Remove the Magento crontab
bin/magento cron:remove
Run cron from the command line
bin/magento cron:run [–group=”<cron group name>”]
–group is specifies the cron group to run
To run the default cron job
bin/magento cron:run –group default
To run the indexing cron job
bin/magento cron:run –group index
Now we are going to add a custom cron in module Dolphin HelloWorld
app/code/Dolphin/HelloWorld/etc/crontab.xml
1 2 3 4 5 6 7 8 | <?xml version="1.0" ?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd"> <groupid="default"> <jobname="dolphin_helloworld_helloword"instance="Dolphin\HelloWorld\Cron\Helloword"method="execute"> <schedule>*/5 * * * *</schedule> </job> </group> </config> |
schedule */5 * * * * it means it will run every five minutes
app/code/Dolphin/HelloWorld/Cron/Helloword.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <?php declare(strict_types=1); namespace Dolphin\HelloWorld\Cron; class Helloword { protected$logger; /** * Constructor * * @param \Psr\Log\LoggerInterface $logger */ publicfunction__construct(\Psr\Log\LoggerInterface$logger) { $this->logger = $logger; } /** * Execute the cron * * @return void */ public function execute() { $this->logger->addInfo("Cronjob Helloword is executed."); } } |
That’s it!
Also like this: Create sales order programmatically in Magento 2
I hope this blog helps you. If you have any further queries regarding this blog write your query in the comment section.