如何在 Magento 2 中创建自定义crontab 定时任务

如何在 Magento 2 中创建自定义 cron job

Magento 2 中的 cron 工作是什么?Magento 中的 Cron 作业有助于执行将在准确的时间和日期系统地运行的脚本。在 Magento 2 中,Cron 作业运行计划任务、重新索引、生成时事通讯、站点地图等。我们应该在哪种情况下使用 cron 作业?cron 作业将是每分钟、每小时、每天或每周重复任务的完美选择。让我们了解更多 Magento 2 中的 Cron 作业,我们将在 Magento 2 中进行与时事通讯订阅相关的实践。我们将在 Magento 2 中创建一个自定义 cron 作业,如果这些客户不这样做,则允许检查所有客户 订阅时事通讯,我们将设置他们的帐户订阅时事通讯。我们将使用默认的 cron 组,此任务将每分钟重复一次。

  • 第 1步:声明名为 Cg_UpdateCron 的新模块
    • 在路径 app\code 中创建命名空间Cg
    • 在路径 app\code\Cg 中创建名为 UpdateCron 的新模块
    • 在路径 app\code\Cg\UpdateCron 中创建名为 registration.php 的新文件
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Cg_UpdateCron',
__DIR__
);
  • 在路径 app\code\Cg\UpdateCron\etc 中创建名为 module.xml 的新文件
    • 第 1 步结束,我已经完成了创建名为 PHPCuong_CustomCronJob 的新模块的代码。
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Cg_UpdateCron" setup_version="2.0.0">
    </module>
</config>
  • 第 2 步:声明一个名为 cg_updatecron _newsletter_subscription 的新作业代码
    • 在路径 app\code\Cg\UpdateCron\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="cg_update_cron_meta_title" instance="Cg\UpdateCron\Cron\MetaTitle" method="execute">
<schedule>* * * * *</schedule>
</job>
</group>
<group id="default">
<job name="test" instance="Cg\UpdateCron\Cron\Test" method="execute">
<schedule>* * * * *</schedule>
</job>
</group>
</config>
  • 在路径 app\code\Cg\UpdateCron\Cron 中创建名为 NewsletterSubscription.php 的新文件
<?php
/**
* Created by PhpStorm.
* User: yshuq
* Date: 2022/7/26
* Time 11:43 AM
*/

namespace Cg\UpdateCron\Cron;

use Magento\Framework\App\ResourceConnection;

class MetaTitle
{
protected $resourceConnection;

public function __construct(
ResourceConnection $resourceConnection
)
{
$this->resourceConnection = $resourceConnection;
}

public function execute()
{
//操作日志更改记录
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/meta_title_update-5-12:00.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);

$connection = $this->resourceConnection->getConnection();
//1.查询meta_title 的属性id
$attributeId = '1';
$table = $connection->getTableName('eav_attribute');
$query = "Select * from " . $table . " WHERE `attribute_code` = 'meta_title' and `frontend_label` = 'Meta Title'";
$logger->info("查询meta title 的 id:".$query);
$result1 = $connection->fetchAll($query);
if (!empty($result1) && count($result1) == 1) {
$attributeId = $result1[0]['attribute_id'];
}

//2.获取所有网站 store_website 循环遍历网站 website_id
$table = $connection->getTableName('store_website');
$query = "Select * FROM " . $table . " where `name` != 'Admin'";
$logger->info("查询所有网站:".$query);
$websiteList = $connection->fetchAll($query);
$logger->info("所有网站list:".\GuzzleHttp\json_encode($websiteList));

if (!empty($websiteList) && count($websiteList) > 0) {
$webId = $websiteName = $query = '';
foreach ($websiteList as $v1 => $j1) {
$websiteName = $j1['name'];
$webId = $j1['website_id'];

//3.根据website_id 循环遍历产品 product_id
$table = $connection->getTableName('catalog_product_website');
$query = "Select * FROM " . $table . " where website_id = " . $webId;
$productList = $connection->fetchAll($query);
$logger->info("根据网站id查询所有产品:".$query);
$logger->info("网站id:".$webId."的全部产品".\GuzzleHttp\json_encode($productList));

if (!empty($productList) && count($productList) > 0) {
foreach ($productList as $v2 => $j2) {
$productId = $j2['product_id'];
$logger->info("product id:" . $productId);
//4.根据website_id 在store表查询出店铺id
$table = $connection->getTableName('store');
$query = "Select * FROM " . $table . " where `website_id` =" . $webId;
$storeList = $connection->fetchAll($query);
$logger->info("根据website_id查询店铺列表" . $query);
$logger->info("网站id: ".$webId."店铺列表".\GuzzleHttp\json_encode($storeList));
if (!empty($storeList) && count($storeList) > 0) {
foreach ($storeList as $v3 => $j3) {
$storeId = $j3['store_id'];

//5.获取 默认店铺admin store_id = 0 的value的值
$table = $connection->getTableName('catalog_product_entity_varchar');
$query = "Select * FROM " . $table . " where store_id = 0 and entity_id = " . $productId
. " and attribute_id = " . $attributeId;
$metaTitleValue0 = $connection->fetchAll($query);
$logger->info("获取默认值sql:".$query);
$logger->info("获取admin点meta title默认值:".\GuzzleHttp\json_encode($metaTitleValue0));

//6.根据店铺id,产品id ,属性id,查询 属性为meta_tile的值,
$query = "Select * FROM " . $table . " where store_id = " . $storeId . " and entity_id = " . $productId
. " and attribute_id = " . $attributeId;
$metaTitleValue1 = $connection->fetchAll($query);
$logger->info("获取当前网站店铺产品的meta title sql:".$query);
$logger->info("获取当前网站店铺产品的meta title 的值:".\GuzzleHttp\json_encode($metaTitleValue1));
//7.组合新值,获取store id = 0 后台默认值。
$mt = explode('-', $metaTitleValue0[0]['value']);
$newMetaTitleValue = $mt[0] . "-" . $websiteName;
//8.meta title 不存在 就添加, 存在,就更新
if (empty($metaTitleValue1) && count($metaTitleValue1) == 0) {
$data = [
'attribute_id' => $attributeId,
'store_id' => $storeId,
'entity_id' => $productId,
'value' => $newMetaTitleValue
];
$logger->info("添加的meta title 的值".\GuzzleHttp\json_encode($data));
$connection->insert($table,$data);
}else{
$id = $metaTitleValue1[0]['value_id'];
$newMetaTitleValue = str_replace("'", ' ', $newMetaTitleValue);
$sql = "UPDATE ".$table." SET `value` = '". $newMetaTitleValue."' WHERE value_id = ".$id;
$logger->info("更新meta title 的值".$sql);
$connection->query($sql);
}
}
}
}
}
}
}
}
}
  • 第 3 步:测试并查看结果 运行以下命令
php bin/magento setup:upgrade --keep-generated 
php bin/magento cache:flush
php bin/magento cron:run

本问参考: