Auto Expire (file) cache

I’m showing a list of events on pretty much every page. Is there a way to auto-expire the cache after a day? Currently past events are shown because of the cache, and my client manually flushes the cache.

I have a few sites with similar requirement. My solution was to schedule a cron job to clean the cache folder on the desired interval. A simple command like this on the cronjob will do it:

rm /home/example.com/site/cache/*

Digital Ocean has a great tutorial on setting up cron jobs.

2 Likes

Unfortunately the hosting does not provide any way of setting up a cron job. So I might have to use a poor man’s cron job instead. :thinking:

I have no experience with them, but what about using external cron job services?

One option would be setup a simple “webhook” consisted of a Kirby route which flushes the cache. You could setup a cronjob on any other computer to ping the Kirby site on that URL using cURL, for example.

Another idea I just had is to run a simple check on every request:

<?php // site.php on the root

$kirby = kirby();

/**
 * Flush the cache daily
 */

// Creates an empty hidden file to store cache's last flush time
$cacheFile = __DIR__ . DS . '.cache';

if (! file_exists($cacheFile)) file_put_contents($cacheFile, '');


// Checks if the file was updated before midnight
$midnight = strtotime('today midnight');

if (filemtime($cacheFile) < $midnight) {

    // If so…
    // Flushes the cache
    kirby()->cache()->flush();

    // Updates the cache file modification time
    touch($cacheFile);
}

Place this code in a site.php file on the site’s root (this file is loaded by Kirby automatically when present, create it if it doesn’t exist already):

Consider this a quick working proof-of-concept. Feel free to improve it, wrap it inside a function, whatever.

3 Likes

That’ll work! Thanks :slight_smile:

External cron job (like https://www.easycron.com) is the easiest way to create cron job, you just need to click to choose some settings to complete an complex cron job configuration.