首页 > 解决方案 > 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();
}

你们应该知道的:

这是 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 ... */

每次我加载页面并浏览网站时都没有任何反应。我想知道我做错了什么?!

感谢您的帮助!

标签: phpwordpresscron

解决方案


我终于发现我的代码发生了什么。我只是把它放在这里以备将来类似的疑问。

解决方案是:不要使用protected方法,而是public为您runner()想要的功能使用方法。


推荐阅读