Cronjob

With this snippet you can create a class with a 'execute' method wich will be executed by the magento cron schedule according to the cron schedule you have configured.

The class will be created within the "Cron" folder of the module.

To build up the cron schedule manually use php bin/magento cron:run

You should find a log in the var/log/system.log after the cronjob has runned.

In the Magento 2 Adminpanel under Stores > Configuration > Advanched > System you change scheduler settings per cron group.

You can create your own groups if you wish. In that case be sure to add extra system settings.

Instead of the <schedule> tag in the crontab.xml you can set a system config path

Example

<config_path>crontab/default/jobs/catalog_product_alert/schedule/cron_expr</config_path>

This way a admin user can configure the cronschedule for this task.

Use the snippet in the Magento 2 module creator.

Files

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="mage2gen_module_test" instance="Mage2Gen\Module\Cron\Test" method="execute">
			<schedule>*/5 * * * *</schedule>
		</job>
	</group>
</config>

Cron/Test.php

<?php
declare(strict_types=1);

namespace Mage2Gen\Module\Cron;

class Test
{

    protected $logger;

    /**
     * Constructor
     *
     * @param \Psr\Log\LoggerInterface $logger
     */
    public function __construct(\Psr\Log\LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * Execute the cron
     *
     * @return void
     */
    public function execute()
    {
        $this->logger->addInfo("Cronjob Test is executed.");
    }
}