Setup wp_schedule_event within a custom plugin

enter image description here

I am using WordPress 4.9.6 and I am trying to create a plugin that pulls data from an external API.

See below my current code:

myPlugin.php

<?php
/**
Plugin Name: myPlugin
description: Get Data via APIs
Version: 1.0
Author: Batman
License: GPLv2 or later
Text Domain: myPlugin
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

require_once 'vendor/autoload.php';

class My_Plugin {

      /**
     * Constructor.
     */
    public function __construct() {
        define( 'MyPlugin_FILE', __FILE__ );
        define( 'MyPlugin_DIR', trailingslashit( dirname( __FILE__ ) ) );
        define( 'MyPlugin_VERSION', '0.0.1' );
        register_activation_hook( basename( MyPlugin_DIR ) . '/' . basename( MyPlugin_FILE ), array( $this, 'activate' ) );
        add_action( 'plugins_loaded', array( $this, 'includes' ) );
        add_action( 'init', array( $this, 'maybe_update' ) );
    }

    public function activate() {
        $this->includes();
        flush_rewrite_rules();
    }

    public function includes() {
        include_once( MyPlugin_DIR . 'includes/WhatToMineAPI.php' );
    }

    /**
     * Maybe update MyPlugin.
     */
    public function maybe_update() {
        $version = get_option( 'MyPlugin_version', 0 );
        if ( version_compare( $version, MyPlugin_VERSION, '<' ) ) {
            $this->create_tables();
            update_option( 'MyPlugin_version', MyPlugin_VERSION );
        }
    }
}
new My_Plugin();

WhatToMineAPI.php

<?php

use GuzzleHttpClient;

class WhatToMineAPI {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action( 'setupCronJob_whatToMine', 'setupCronJob');
        add_action( 'update_whatToMine_api', 'updateWhatToMineAPI');

        // variables
        $whatToMineURL = "http://whattomine.com/coins.json";
    }

    public function setupCronJob() {
        //Use wp_next_scheduled to check if the event is already scheduled
        $timestamp = wp_next_scheduled( 'update_whatToMine_api' );

        //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', 'update_whatToMine_api' );
        }
    }

    public function updateWhatToMineAPI() {

        $client = new GuzzleHttpClient();

        $response = $client->request('GET', $whatToMineURL);

    }


}
new WhatToMineAPI();

I have installed the plugin WP-Control to get an overview of my running cron-jobs. However, my cron-job update_whatToMine_api cannot be found within the table?

Is my current cron-setup wrongly done?

I appreciate your replies!

Read more here:: Setup wp_schedule_event within a custom plugin

Leave a Reply

Your email address will not be published. Required fields are marked *