Skip to content

Instantly share code, notes, and snippets.

@magevision
Last active June 8, 2023 08:38
Show Gist options
  • Save magevision/6663f182add9f569bdf415bac56f2ff0 to your computer and use it in GitHub Desktop.
Save magevision/6663f182add9f569bdf415bac56f2ff0 to your computer and use it in GitHub Desktop.
CreateACronWithConfigPath
<?php
declare(strict_types=1);
namespace MageVision\Blog89\Cron;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
class Post
{
public const XML_PATH_ENABLE = 'blog89/post/enabled';
protected ScopeConfigInterface $scopeConfig;
/**
* @param ScopeConfigInterface $scopeConfig
*/
public function __construct(
ScopeConfigInterface $scopeConfig
) {
$this->scopeConfig = $scopeConfig;
}
/**
* Execute cron
*
* @return void
*/
public function execute()
{
// check if enabled
if (!$this->scopeConfig->isSetFlag(
self::XML_PATH_ENABLE,
ScopeInterface::SCOPE_STORE
)
) {
return;
}
//Add your code
}
}
<?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 instance="MageVision\Blog89\Cron\Post" method="execute" name="magevision_blog69_post_cron">
<config_path>crontab/default/jobs/magevision_blog89_cron/schedule/cron_expr</config_path>
</job>
</group>
</config>
<?php
declare(strict_types=1);
namespace MageVision\Blog89\Model\Config\Backend;
use Magento\Cron\Model\Config\Source\Frequency;
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Config\Value;
use Magento\Framework\App\Config\ValueFactory;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
class Post extends Value
{
public const CRON_STRING_PATH = 'crontab/default/jobs/magevision_blog89_cron/schedule/cron_expr';
protected ValueFactory $configValueFactory;
/**
* @param Context $context
* @param Registry $registry
* @param ScopeConfigInterface $config
* @param TypeListInterface $cacheTypeList
* @param ValueFactory $configValueFactory
* @param AbstractResource|null $resource
* @param AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
Context $context,
Registry $registry,
ScopeConfigInterface $config,
TypeListInterface $cacheTypeList,
ValueFactory $configValueFactory,
AbstractResource $resource = null,
AbstractDb $resourceCollection = null,
array $data = []
) {
$this->configValueFactory = $configValueFactory;
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}
/**
* After save handler
*
* @return $this
* @throws LocalizedException
*/
public function afterSave()
{
$time = $this->getData('groups/post/fields/time/value');
if (empty($time)) {
$time = explode(
',',
$this->_config->getValue(
'blog89/post/time',
$this->getScope(),
$this->getScopeId()
) ?: '0,0,0'
);
$frequency = $this->_config->getValue(
'blog89/post/frequency',
$this->getScope(),
$this->getScopeId()
);
} else {
$frequency = $this->getData('groups/post/fields/frequency/value');
}
$frequencyWeekly = Frequency::CRON_WEEKLY;
$frequencyMonthly = Frequency::CRON_MONTHLY;
$cronExprArray = [
(int)$time[1], # Minute
(int)$time[0], # Hour
$frequency == $frequencyMonthly ? '1' : '*', # Day of the Month
'*', # Month of the Year
$frequency == $frequencyWeekly ? '1' : '*', # Day of the Week
];
$cronExprString = join(' ', $cronExprArray);
try {
$configValue = $this->configValueFactory->create();
$configValue->load(self::CRON_STRING_PATH, 'path');
$configValue->setValue($cronExprString)->setPath(self::CRON_STRING_PATH)->save();
} catch (\Exception $e) {
throw new LocalizedException(__('We can\'t save the Cron expression.'));
}
return parent::afterSave();
}
}
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="magevision" translate="label" sortOrder="1000">
<label>MageVision Blog Posts</label>
</tab>
<section id="blog89" translate="label" type="text" sortOrder="1012" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Blog Post 89</label>
<tab>magevision</tab>
<resource>MageVision_Blog89::blog89_configuration</resource>
<group id="post" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Generation Settings</label>
<field id="enabled" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
<label>Enabled</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="time" translate="label" type="time" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Start Time</label>
<depends>
<field id="enabled">1</field>
</depends>
</field>
<field id="frequency" translate="label" type="select" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Frequency</label>
<source_model>Magento\Cron\Model\Config\Source\Frequency</source_model>
<backend_model>MageVision\Blog89\Model\Config\Backend\Post</backend_model>
<depends>
<field id="enabled">1</field>
</depends>
</field>
</group>
</section>
</system>
</config>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment