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;
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With