Deleting External Cache Directory Periodically

我与影子孤独终老i 提交于 2020-01-16 00:45:25

问题


For my app I store map images in a cache on the external storage as to reduce calls to the API that I am using. Since this data is map data, it is subject to change over time. As a result these images should be updated every-so-often.

How can I programmatically delete the cache directory periodically? Say for example, every week.

Some extra thoughts: Perhaps deleting the entire directory is not the best way to go about it. Perhaps I can check the "freshness" of each image, and delete the old ones?


回答1:


Yes, it's usually a good idea to limit your cache with some method or another. Some caches have fixed sizes, and older content is removed once your cache size is exceeded. This size could be a count of the number of items or a size in disk space. Some caches have TTLs for each item (or the same TTL for all items) and so items expire after a certain time. Some caches may never expire. Perhaps it is bounded in size by the number of possible items that would be cached in the first place. Any of these approaches are valid, though some may be more appropriate for certain scenarios than others.

The "freshness" idea is probably an approach I'd consider. It's the same as the TTL. Basically you want to set a length of time that your cache item will live for. Store this cache time along with the cache data, then check it whenever reading the cache data. If it's past the expiration date, you can delete that cache file and retrieve the map data from the API again (and cache that). You could probably do something with just reading the file creation time too if you don't want to store a date separately and have a fixed lifespan hard-coded or configurable in your application.

Update to address comments:

I've used hashing the URL as the filename before too. Just be aware that there's a possibility of collisions (highly dependent on your hash algorithm and your data set of course). Also, if you're going through a lot of URLs, the performance of your hash algorithm might matter too.

Storing that cache metadata in a text file is fine, especially if you don't have a ton of URLs. You'll want to be careful about how you update that text file though. You could easily corrupt it if you're not careful and access it from multiple threads without proper synchronization. If you have a lot of data, another option you can consider is using a database. If you do store this cache metadata in a file--whether database or text file--you can avoid all the problems with hashing by using a different scheme for your filenames. You could just increment in hex or base 36 for example.



来源:https://stackoverflow.com/questions/8219999/deleting-external-cache-directory-periodically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!