├── readme.md └── src └── WP_Cron.php /readme.md: -------------------------------------------------------------------------------- 1 | # WP_Cron 2 | 3 | 4 | ### Clean API into WordPress's Cron System 5 | WP_Cron is a simple and easy to use class for defining cron events in WordPress. Simply, define a class extending WP_Cron, set the frequency of the cron event using the $every property and then write the code you want to execute in the handle() method. 6 | 7 | 8 | ```php 9 | 30, 15 | 'minutes' => 15, 16 | 'hours' => 1, 17 | ]; 18 | 19 | public function handle(){ 20 | $response = file_get_contents('http://api.openweathermap.org/data/2.5/weather?id=2172797'); 21 | $json = json_decode($response); 22 | if($json === NULL && json_last_error() !== JSON_ERROR_NONE){ 23 | return; 24 | } 25 | if(isset($json->weather[0]->description)){ 26 | update_option('london_weather', $json->weather[0]->description); 27 | } 28 | } 29 | } 30 | 31 | UpdateLondonWeather::register(); 32 | ``` 33 | -------------------------------------------------------------------------------- /src/WP_Cron.php: -------------------------------------------------------------------------------- 1 | getShortName(); 8 | return 'wp_cron__'. strtolower($class); 9 | } 10 | 11 | public function schedule(){ 12 | return 'schedule_'. $this->slug(); 13 | } 14 | 15 | public function calculateInterval(){ 16 | 17 | if(!is_array($this->every)){ 18 | throw new Exception("Interval must be an array"); 19 | } 20 | 21 | if(!(count(array_filter(array_keys($this->every), 'is_string')) > 0)){ 22 | throw new Exception("WP_Cron::\$interval must be an assoc array"); 23 | } 24 | 25 | $interval = 0; 26 | $multipliers = array( 27 | 'seconds' => 1, 28 | 'minutes' => 60, 29 | 'hours' => 3600, 30 | 'days' => 86400, 31 | 'weeks' => 604800, 32 | 'months' => 2628000, 33 | ); 34 | 35 | foreach($multipliers as $unit => $multiplier){ 36 | if(isset($this->every[$unit]) && is_int($this->every[$unit])){ 37 | $interval = $interval + ($this->every[$key] * $multiplier); 38 | } 39 | } 40 | 41 | return $interval; 42 | } 43 | 44 | public function scheduleFilter($schedules){ 45 | $interval = $this->calculateInterval(); 46 | 47 | if(!in_array($this->schedule(), array_keys($schedules))){ 48 | $schedules[$this->schedule()] = array( 49 | 'interval' => $interval, 50 | 'display' => 'Every '. floor($interval / 60) .' minutes', 51 | ); 52 | } 53 | 54 | return $schedules; 55 | } 56 | 57 | public static function register(){ 58 | $class = get_called_class(); 59 | $self = new $class; 60 | $slug = $self->slug(); 61 | 62 | add_filter('cron_schedules', array($self, 'scheduleFilter')); 63 | 64 | if(!wp_next_scheduled($slug)){ 65 | wp_schedule_event(time(), $self->schedule(), $slug); 66 | } 67 | 68 | if(method_exists($self, 'handle')){ 69 | add_action($slug, array($self, 'handle')); 70 | } 71 | } 72 | } --------------------------------------------------------------------------------