Automatic refresh caches after expire time

Hello

I use a content generation system by taking different xml feeds. I have enabled kirby caches to make sure that the pages load almost immediately and it works fine.

However, when I get to my page and the caches have expired, it can take about 10 seconds to load before the page is fully loaded.

I’m not a cache expert, but I’ll try to ask my question: is there a way to make an automatic request to refresh these caches outside of a visitor request? Ideally, I’d like to never have these loading times when visiting pages.

Do you have any ideas?

private function fetchRemoteData($url) {
      $request = @file_get_contents($url);
      if ($request !== false) {
         $data = Xml::parse($request);
         return $data;
      }
      return null;
   }

   public function children(): Kirby\Cms\Pages
   {
      if ($this->children instanceof Pages) {
         return $this->children;
      }

      $kirby = kirby();
      $apiCache = $kirby->cache('api');
      $pages = [];
      $cacheDuration = 3600; //  (1 hour)

      /**** XML Feed ******/     
      $xmlUrl = 'https://url.com/feed.xml';
      $xmlCacheKey = 'xmlData';
      $xmlResults = $apiCache->get($xmlCacheKey);
      if ($xmlResults === null) {
         $xmlResults = $this->fetchRemoteData($xmlUrl);
         $apiCache->set($xmlCacheKey, $xmlResults, $cacheDuration);
      }
      $xmlItems = $xmlResults['entry'] ?? [];
      foreach ($xmlItems as $item) {
         $pages[] = $this->createPageFromAtomEntryXML($item);
      }

....

      return $this->children = Pages::factory($pages, $this);
   }

You could use a cron job to fetch the data and recreate the cache every hour.

Well, thank you, I didn’t know about cron jobs; a new world might be opening up for me! Thanks!

Hello

I’m coming back with the code I tried. The cron is well executed but this create a folder named “_” instead of “mywebsite.com” inside the cache folder. Do you know why ?

<?php

ini_set('memory_limit', '256M');
ini_set('max_execution_time', '300'); 

require __DIR__ . '/../../kirby/bootstrap.php';

$kirby = kirby();

if ($kirby->cache('api')) {
    $kirby->cache('api')->flush();
} 

$pages = $kirby->site()->pages()->index();

foreach ($pages as $page) {
    $page->render(); 
}

So, I’ve deeply searched previous topics and find this one

Saying that $_SERVER['SERVER_NAME'] = "https://example.com"; is helpful to force Kirby to set caches into the right folder.

Solved !

indeed :slight_smile:

Glad you figured it out :+1: