Magento 2 Guide: How to Create a Cron Job
Cron jobs are automated tasks that Magento 2 can run at scheduled intervals — such as sending emails, syncing inventory, or cleaning logs. In this blog, Mavenbird will show you how to create a simple custom cron job in Magento 2.
Step 1: Create cron group (optional)
File: 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="mavenbird_custom_cron" instance="Mavenbird\CronJob\Cron\CustomTask" method="execute">
<schedule>*/5 * * * *</schedule>
</job>
</group>
</config>
Note: The above cron runs every 5 minutes.
Step 2: Create Cron Class
File: Cron/CustomTask.php
<?php
namespace Mavenbird\CronJob\Cron;
class CustomTask
{
public function execute()
{
// Your logic here
file_put_contents(BP . '/var/log/mavenbird_cron.log', 'Cron executed at ' . date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
}
}
Step 3: Enable and Test
- Run:
php bin/magento setup:upgrade
- Run:
php bin/magento cron:run
- Check log file:
var/log/mavenbird_cron.log
Conclusion
That’s it! Your cron job is now working in Magento 2. You can customize the logic inside execute()
to suit your needs.
Need help with Magento 2 customization or automation? Reach out to Mavenbird — we make Magento work better for your business.
Stay tuned for more Magento 2 tips from the Mavenbird team!
Please complete your information below to login.