WordPress' relationship with cron is touchy. It has it's own version, wp-cron which isn't so much cron as a check when people visit your site of things your site needs to do. The problem is that if no one visits your site… nothing runs. That's why you sometimes have posts that miss schedules.

One possible solution is to use what we call 'alternate cron' to trigger your jobs. That works pretty well as it means I can tell a server "Every 10 minutes, ping my front page and trigger events."

But in this case, I didn't want that. I receive enough traffic on this site that I felt comfortable trusting in WP cron, so what I wanted was every hour for a specific page to be visited. This would prompt the server to generate the cached content if needed (if not, it just loads a page).

WordPress Plugin

I'm a huge proponent of doing things the WordPress way for WordPress. This method comes with a caveat of "Not all caching plugins will work with this."

I'm using Varnish, and for me this will work, so I went with the bare simple code:

class LWTV_Cron {

	public $urls;
	
	/**
	 * Constructor
	 */
	public function __construct() {

		// URLs we need to prime the pump on a little more often than normal
		$this->urls = array(
			'/statistics/',
			'/statistics/characters/',
			'/statistics/shows/',
			'/statistics/death/',
			'/statistics/trends/',
			'/characters/',
			'/shows/',
			'/show/the-l-word/',
			'/',
		);

		add_action( 'lwtv_cache_event', array( $this, 'varnish_cache' ) );

		if ( !wp_next_scheduled ( 'lwtv_cache_event' ) ) {
			wp_schedule_event( time(), 'hourly', 'lwtv_cache_event' );
		}
	}

	public function varnish_cache() {
		foreach ( $this->urls as $url ) {
			wp_remote_get( home_url( $url ) );
		}
	}

}

new LWTV_Cron();

Yes it's that site. This very simple example shows that I have a list of URLs (slugs really) I know need to be pinged every hour to make sure the cache is cached. They're the slowest pages on the site (death can take 30 seconds to load) so making sure the cache is caught is important.

Reader Interactions

Comments

  1. Why the photo of Gaelic football?
    A local team?

Leave a Reply

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

%d bloggers like this: