This is Magento 1.9.x CE.
I have created some modules that implement a helper to pull data from various APIs and save the output in Magento's cache using the
_saveCache method in
Mage_Core_Helper_Abstract. The idea here is that if the cache item already exists and is not expired then it is loaded from cache, otherwise an API call is made.
This works well but has the potential to delay page load for the visitor if they hit a page when the item cache is expired and therefore the remote API needs calling.
To workaround this I figured I'd implement a cron task to call the API instead.
Can anyone think of a way to do this which still keeps API calls to a minimum (i.e. only call the API when the cache is nearly expired) but ensures that the cached item is always available?
For reference I am thinking of caching results for around 6 hours but this would be configurable.
I was thinking some kind of logic like this:
- Run the cron every minute:
- Check whether the item exists in cache
- if not: make API call, store result as cache item, exit
- if so: continue
- Check whether the cache lifetime is approaching (how to do this bit??)
- if so: make API call, store result as cache item, exit
- if not, exit
So really, the question boils down to how can I check whether the cache lifetime is approaching? And/or can anyone think of a better way to do this?