Created
February 26, 2019 06:19
-
-
Save jondcampbell/6da10efc4eb250176dc6b4cb6a06373a to your computer and use it in GitHub Desktop.
WordPress Cron running in a php class on a custom schedule
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace MyProject; | |
/** | |
* Cron Pull | |
* | |
* Cron functionality for pulling data on a regular basis | |
* | |
* @package MyProject | |
*/ | |
use WP_Query; | |
class Cron_Pull { | |
/** | |
* Holds the singleton instance. | |
* | |
* @static | |
* @var object | |
*/ | |
private static $_instance = null; | |
/** | |
* The cron action hook we will be using. | |
* | |
* @var string | |
*/ | |
private $_cron_hook = 'myproject_pull'; | |
/** | |
* Get a reference to the singleton. | |
* | |
* @return object The singleton instance. | |
*/ | |
public static function instance() { | |
if ( ! isset( self::$_instance ) ) { | |
self::$_instance = new self(); | |
} | |
return self::$_instance; | |
} | |
/** | |
* Cron_Pull constructor. | |
*/ | |
public function __construct() { | |
register_deactivation_hook( MYPROJECT_PULL_PLUGIN_FILE, [ $this, 'deactivated' ] ); | |
} | |
/** | |
* Initialize this class when the plugin loads. | |
*/ | |
public function init() { | |
add_action( $this->_cron_hook, [ $this, 'run_cron' ] ); | |
add_filter( 'cron_schedules', [ $this, 'cron_intervals' ] ); | |
if ( ! wp_next_scheduled( $this->_cron_hook ) ) { | |
wp_schedule_event( time(), 'myproject_custom_schedule', $this->_cron_hook ); | |
} | |
} | |
/** | |
* Filter the cron_intervals to add our custom schedule to the existing ones. | |
* | |
* @param array $schedules The existing cron schedules. | |
* @return mixed Send back the array of all cron schedules. | |
*/ | |
public function cron_intervals( $schedules ) { | |
$schedules['myproject_custom_schedule'] = [ | |
'interval' => intval( MYPROJECT_PULL_CRON_SCHEDULE_DAYS ) * DAY_IN_SECONDS, | |
'display' => 'Every ' . MYPROJECT_PULL_CRON_SCHEDULE_DAYS . ' days', | |
]; | |
return $schedules; | |
} | |
/** | |
* Main functionality of this class, running the cron function. | |
*/ | |
public function run_cron() { | |
// TODO: Do the stuff here! | |
} | |
/** | |
* When the plugin deactivates we want to unschedule our cron event. | |
*/ | |
public function deactivated() { | |
wp_unschedule_event( wp_next_scheduled( $this->_cron_hook ), $this->_cron_hook ); | |
} | |
} | |
define( 'MYPROJECT_PULL_PLUGIN_FILE', __FILE__ ); | |
define( 'MYPROJECT_PULL_CRON_SCHEDULE_DAYS',14) | |
add_action( 'plugins_loaded', [ Cron_Pull::instance(), 'init' ] ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment