Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 7 temporary cache item won't expire

I have a fairly expensive server call that I need to cache for 30 seconds. It seems however that I can not get the cache to expire.

In the code below, after the first time it caches, it will never get past $return->cache_data, even after the time() + 30 seconds.

Note, I can even print $cache->expire and it is definitely set to a time past 30 seconds ago and never updates.

I've manually cleared cache many times to confirm I get the same results.

Does anything look wrong with this?

function mymodule_get_something($id) {
  // set the unique cache id
  $cid = 'id-'. $id;

  // return data if there's an un-expired cache entry
  //  *** $cache ALWAYS gets populated with my expired data
  if ($cache = cache_get($cid, 'cache_mymodule')) {
    return $cache->data;
  }

  // set my super expensive data call here
  $something = array('Double Decker Taco', 'Burrito Supreme');

  // set the cache to expire in 30 seconds
  cache_set($cid, $something, 'cache_mymodule', time() + 30);

  // return my data
  return $something;
}
like image 483
Coder1 Avatar asked Nov 13 '11 20:11

Coder1


1 Answers

There's nothing wrong with your code as such, I think the problem is in how cache_set behaves. From the docs page, passing a UNIX timestamp:

Indicates that the item should be kept at least until the given time, after which it behaves like CACHE_TEMPORARY.

CACHE_TEMPORARY behaves like this:

Indicates that the item should be removed at the next general cache wipe.

My best guess is that because you're not implicitly forcing that general cache wipe (using cache_clear_all()) the cache object will persist.

I think a simple way around it would just be to manually test the expiry time after your cache check, and let it fall through to re-setting that cache object if it has expired:

if ($cache = cache_get($cid, 'cache_mymodule')) {
  if ($cache->expire > REQUEST_TIME) {
    return $cache->data;
  }
}
like image 107
Clive Avatar answered Oct 02 '22 13:10

Clive