Please add below files in your custom module for custom cron:-
Path: \Vendor\SampleModule\Cron\AddItem.php
<?php
namespace Vendor\SampleModule\Cron;
use Vendor\SampleModule\Model\ItemFactory;
use Vendor\SampleModule\Model\Config;
class AddItem
{
private $itemFactory;
private $config;
//add your dependency here
public function __construct(ItemFactory $itemFactory, Config $config)
{
$this->itemFactory = $itemFactory;
$this->config = $config;
}
public function execute()
{
//you can add your logic here
if ($this->config->isEnabled()) {
$this->itemFactory->create()
->setName('Scheduled item')
->setDescription('Created at ' . time())
->save();
}
}
}
Path: \Vendor\SampleModule\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="vendorAddItem" instance="Vendor\SampleModule\Cron\AddItem" method="execute">
<schedule>*/5 * * * *</schedule>
</job>
</group>
</config>
Please check your cron job using below command:-
php bin/magento cron:run