Today we learn how to Create Cron Job Programmatically 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.
Here are some commands below
Install cron:-
[dt_highlight color=”” text_color=”” bg_color=””]bin/magento cron:install [–force][/dt_highlight]
Use –force to rewrite an existing Magento crontab.
To view the crontab:-
[dt_highlight color=”” text_color=”” bg_color=””]crontab -l[/dt_highlight]
Remove the Magento crontab:-
[dt_highlight color=”” text_color=”” bg_color=””]bin/magento cron:remove[/dt_highlight]
Run cron from the command line:-
[dt_highlight color=”” text_color=”” bg_color=””]bin/magento cron:run [–group=”<cron group name>”][/dt_highlight] –group is specifies the cron group to run
To run the default cron job:-
[dt_highlight color=”” text_color=”” bg_color=””]bin/magento cron:run –group default[/dt_highlight]
To run the indexing cron job:–
[dt_highlight color=”” text_color=”” bg_color=””]bin/magento cron:run –group index[/dt_highlight]
Now we are going to add a custom cron in module Dolphin HelloWorld
app/code/Dolphin/HelloWorld/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"> <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
<?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.