Creating a simple module to clear the Drupal 4.7 cache
The problem
Drupal offers some powerful caching features, but they are by no means perfect as we discovered when building the site http://www.booktribes.com.
Booktribes uses some simple custom blocks to display some semi-dynamic content, content such as the "rotating" lists of celebrity favourite books. Turning on Drupal page caching offers a significant performance boost to the site, but it means that our dynamic front page content suddenly becomes static - which is bad news.
So, the solution - write a simple module that will refresh the page cache a a given interval, every 15 minutes the cached pages are regenerated - its win win, the users see the content updating frequently and the server still feels the benefits of the page caching. Of course - it is worth remembering that Drupal will only cache pages for non-authenticated users.
Oh, and we weren't the only ones to have similar problems - check out this thread http://lists.drupal.org/archives/development/2006-07/msg00630.html
The solution - the Cacheclear module
The module is actually very simple - it has one setting, the time period between cache refreshes and only one small piece of functionality which checks to see if the cache needs clearing, and performs the clear if required. The module's project page can be found here http://drupal.org/project/cacheclear
The full module code :
<?php
function cacheclear_help($section) {
switch ($section) {
case 'admin/modules#description':
return t('Clear the PAGE cache after a given period of time.');
}
}
function cacheclear_settings() {
$period = drupal_map_assoc(array(0, 60, 180, 300, 600, 900, 1800, 2700, 3600, 10800, 21600, 32400, 43200, 86400), 'format_interval');
$period[0] = t('never');
$form['cacheclear_time'] = array( '#type' => 'select', '#title' => t('Clear page cache every X minutes'), '#default_value' => variable_get('cacheclear_time', 0), '#options' => $period, '#description' => t('Pages cached by Drupal are not automatically refreshed - this can be an issue if your site is displaying some dynamic content.')
);
return $form;
}
function cacheclear_init() {
$time_period = variable_get('cacheclear_time',0);
if ($time_period && (variable_get('cacheclear_last_clear',0)+$time_period < time())){
cache_clear_all("http://",true); //clear all pages
variable_set('cacheclear_last_clear',time()); //set the last clear time
}
}
?>Lets walk through the code:
<?php
function cacheclear_help($section)
?><?php
function cacheclear_settings()
?><?php
function cacheclear_init()
?>Alternative solutions
There are several other ways we could have written this module - the most obvious would have been to utilise hook_cron, but many (most??) sites are only running their cron jobs every 15 minutes +
UPDATE : Drupal 5 version of this module has now been released.


