Drupal 7 Temporary Caching Element Will Not Expire

I have a rather expensive server call that I need to cache for 30 seconds. It seems, however, that I cannot get the cache expiration date.

In the code below, after the first half-time of caching, it will never pass $ return-> cache_data even after a time of () + 30 seconds.

Notice, I can even print $ cache-> expire, and it is definitely set to the time elapsed 30 seconds ago and is never updated.

I manually cleared the cache many times to confirm that I am getting the same results.

Is something wrong with this?

function mymodule_get_something($id) { // set the unique cache id $cid = 'id-'. $id; // return data if there 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; } 
+6
source share
1 answer

There is nothing wrong with your code as such, I think the problem is how cache_set . On the docs page, pass the UNIX timestamp:

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

CACHE_TEMPORARY behaves as follows:

Indicates that the item should be deleted the next general cache clear.

My best guess is that since you do not implicitly delete the shared cache (using cache_clear_all() ), the cache object will persist.

I think a simple way around this is to simply manually check the expiration time after checking the cache and letting it fail in order to reinstall this cache object if it has expired:

 if ($cache = cache_get($cid, 'cache_mymodule')) { if ($cache->expire > REQUEST_TIME) { return $cache->data; } } 
+10
source

Source: https://habr.com/ru/post/901392/


All Articles