Themergency fooplugins.com

Master The WordPress Cron

| 0 comments

This is day 19 of my WordPress Developer Advent Calendar.

If you have ever worked with the WordPress Cron before, you know how difficult it is to test and debug. For those who do not know what the WordPress Cron is, in a nutshell, it allows you to schedule jobs/tasks to run at specific time intervals. Very handy indeed. For example, every week, you want to check for new users who have signed up to your blog and send them a thank you email.

Schedule Events

You call the wp_schedule_event function to setup jobs in the WordPress Cron. An example:

if ( ! wp_next_scheduled( 'send_flowers_to_mom' ) ) {
	wp_schedule_event( current_time( 'timestamp' ), 'weekly', 'send_flowers_to_mom' );
}

This first checks if the job exists, and then creates it if needed. I am not going to go into more detail than that. For a thorough walkthrough of scheduling jobs check out the very detailed post Schedule Events Using WordPress Cron.

Which Cron Jobs Are Active?

So how do you know which cron jobs are active, and more importantly, when will a certain job execute next? There are 2 plugins which can help. The one is a Debug Bar add-on plugin called Debug Bar Cron. This adds a new tab to the Debug Bar dashboard where you can see all active jobs and also see when they will be executed next:

debug_bar_cron

 

The  other plugin I use is called WP Control. It allows you to view and control what is scheduled in the cron. It also allows you to add a job from the WP Control page in the admin. But my favourite feature is the ability to run any job right now. This is a great way to test your scheduled jobs:

wp_control

 

Crons And Xdebug

If you use Xdebug to debug your WordPress code (and I highly recommend that you do!) then you will notice that when cron jobs are executed, you cannot step into your code to debug what is going on. The reason for this is the way that the WordPress cron executes these jobs. If you look at the code inside cron.php, you will notice it does the following:

wp_remote_post( $cron_request['url'], $cron_request['args'] );

You cannot debug code that is called via wp_remote_post, because for xdebug to work, you need to activate it by specifying a specific querystring or cookie. The only way to do this with wp_remote_post calls, is to intercept the calls and add a XDEBUG_SESSION cookie. I created a very simple little plugin that does just that. It is called XDebug Http Requests and the code is available on Github.

Master The Cron

With this combination of plugins, you will be able to:

  1. See which cron jobs are currently scheduled.
  2. Manually execute a specific job.
  3. Step into the code and debug what is actually happening.