First of all: if you haven’t read it already, please check the official documentation on WP-Cron.
The problem in your code is this line
add_action( 'setupCronJob_whatToMine', 'setupCronJob');
You’re defining a new action setupCronJob_whatToMine
and add the setupCronJob
method to it. But as this is a custom action you just created, it will never be called (eg via do_action('setupCronJob_whatToMine');
).
So instead of adding it to an action, you can call setupCronJob()
directly to set up the event scheduling.
You can do it in the init
action. However, this will add the logic to every page load, which is unnecessary. A cron like needs to be set up only once.
So I’d add the Cron in the activation hook (and don’t forget to remove it in the deactivation 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);
}
}
Side note: When working with classes, you need to beware. Either use add_action('...', array($this, 'methodName'))
but then you need $this
or similar defined.
Alternatively you can use static
methods like so add_action('...', array(MySuperClass::class, 'staticMethodName'))