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.
Comments
3 responses to “Cron Caching”
Why the photo of Gaelic football?
A local team?
Just a random stock photo of someone missing a catch 🙂 It amused me.
Header photos for my posts are usually only topical if you think they’re a play on words or puns.
I get the pun now – the ‘t’ is silent 🙂
I’m in Ireland and Gaelic football is the national sport. And it’s all amateur, no pros!
Aside: I often use standalone scripts (with WP_USE_THEMES set to false) and real cron to run stuff that may take a while, though I do secure them (something you advised me a long time ago)
http://www.damiencarbery.com/2017/01/standalone-wordpress-scripts-what-do-they-do-how-to-secure-them/