首先:如果你还没有读过,请检查official documentation on WP-Cron.
代码中的问题是这一行
add_action( \'setupCronJob_whatToMine\', \'setupCronJob\');
您正在定义新操作
setupCronJob_whatToMine
并添加
setupCronJob
方法。但由于这是您刚刚创建的自定义操作,因此永远不会调用它(例如通过
do_action(\'setupCronJob_whatToMine\');
).
因此,您可以调用setupCronJob()
直接设置事件调度。
你可以在init
行动但是,这将为每个页面加载添加逻辑,这是不必要的。类cron只需设置一次。
所以我要在activation hook (不要忘记将其从停用挂钩中拆下)。
Simple code example:
MyPlugin.php
register_activation_hook( __FILE__, array(My_Plugin::class, \'activate\') );
register_deactivation_hook( __FILE__, array(My_Plugin::class, \'deactivate\') );
class MyPlugin
{
public static function activate()
{
WhatToMineAPI::setupCronJob();
}
public static function deactivate()
{
WhatToMineAPI::unsetCronJob();
}
// your other methods
}
WhatToMineAPI.php
class WhatToMineAPI
{
const CRON_HOOK = \'update_whatToMine_api\';
public static function setupCronJob()
{
//Use wp_next_scheduled to check if the event is already scheduled
$timestamp = wp_next_scheduled( self::CRON_HOOK );
//If $timestamp === false schedule daily backups since it hasn\'t been done previously
if( $timestamp === false ){
//Schedule the event for right now, then to repeat daily using the hook \'update_whatToMine_api\'
wp_schedule_event( time(), \'twicedaily\', self::CRON_HOOK );
}
}
public static function unsetCronJob()
{
// Get the timestamp for the next event.
$timestamp = wp_next_scheduled( self::CRON_HOOK );
wp_unschedule_event( $timestamp, self::CRON_HOOK );
}
public function __construct()
{
add_action(self::CRON_HOOK, array($this, \'updateWhatToMineAPI\'));
}
public function updateWhatToMineAPI()
{
$client = new GuzzleHttp\\Client();
$response = $client->request(\'GET\', $whatToMineURL);
}
}
旁注:在上课时,你需要小心。要么使用
add_action(\'...\', array($this, \'methodName\'))
但是你需要
$this
或类似定义。
或者,您可以使用static
像这样的方法add_action(\'...\', array(MySuperClass::class, \'staticMethodName\'))