php - Wordpress 自定义 wp-cron 类不会触发预定的处理程序
问题描述
因此,我们使用 Bedrock 来帮助对我们的产品进行编码,我需要构建一个通用类来处理自定义 cronjobs。
这是基本的 cronjob 类:
<?php
namespace namespace\to\the\class;
abstract class CronHelper extends AbstractHelper {
/** Declare all attributes and other methods */
/**
* Setup the custom cronjob
*/
protected function init() {
$this->setAlias(DEFAULT_CRON_ALIAS);
$this->setInterval(DEFAULT_CRON_INTERVAL);
$this->setDisplay(DEFAULT_CRON_DISPLAY);
}
/**
* Start the cronjob
*/
public function start() {
add_filter('cron_schedules', array($this,'customInterval'));
add_action($this->getAlias(), array($this,'runner'));
if (! wp_next_scheduled($this->getAlias())) {
wp_schedule_event(time(), "{$this->getAlias()}_interval", $this->getAlias());
}
}
/**
* The custom interval builder
*
* @return array The custom interval setup
*/
public function customInterval() {
$scheduler["{$this->getAlias()}_interval"] = array('interval' => $this->getInterval(),'display' => $this->getDisplay());
return $scheduler;
}
/**
* The scheduler implementation function
*/
protected abstract function runner();
}
你们应该知道的:
- AbstractHelper 是一个单例类
- 我压制了吸气剂/二传手
- 该方法
start()
在我们网站的每个页面加载时触发
这是 CronHelper 类的一种实现:
<?php
namespace namespace\to\the\class;
class TestCron extends CronHelper {
protected function runner() {
// Try to print something on the nginx's error logs
error_log('Running inside the class TestCron');
// Create a random file just for testing
$file = fopen('./cronjob.txt', 'w');
fwrite($file, sprintf('Hello World [%d]', time()));
fclose($file);
}
}
这就是我实例化一切的方式,记住这段代码每次都会执行:
<?php
/** A lot of code above ... */
// Start the Test Cronjob
TestCron::getInstance()->setAlias('test_cron')
->setDisplay('Test Cronjob')
->setInterval(5) // Fire every 5 seconds
->start();
/** A lot of code below ... */
每次我加载页面并浏览网站时都没有任何反应。我想知道我做错了什么?!
感谢您的帮助!
解决方案
我终于发现我的代码发生了什么。我只是把它放在这里以备将来类似的疑问。
解决方案是:不要使用protected
方法,而是public
为您runner()
想要的功能使用方法。
推荐阅读
- python - 正则表达式在搜索时忽略某些字符
- r - R通过小标题滑动窗口
- javascript - WebSocket 握手期间的 WebSockets WS 错误:意外的响应代码:200
- matlab - 在 for 循环中按唯一列值提取行分组。Matlab中的多个输出
- r - 如何在 R 中创建全基因组读取密度图(用于细菌基因组)
- java - 更新 JHipster 后不提供 Angular 组件,仅提供根 index.html
- r-markdown - 如何在用 kable 生成的表格的脚注中插入引文?
- javascript - 使用 Swal 库时,不知道是因为 api 才得到的,为什么?
- javascript - ApexChart 更新系列和标签
- assembly - x86 解释,函数参数和局部变量的数量