Cache, time consuming subroutines or paid api calls. It is thread safe, and can be used from different processes using the same cache_dir
#!/usr/bin/perl
use Cache::SimpleDir;
my $cache = SimpleDir->new(
cache_dir => '/tmp/cache/key1',
callback => 'GetWeather',
expire_sec => 1800,
verbose => 'false') or die $SimpleDir::ERROR;
my $where_are_my_data = $cache->get('a','b','c') or die "oups $SimpleDir::ERROR\n";
print "data are at: $where_are_my_data\n";
# How to get and cache new data
sub GetWeather {
my $dir = shift;
open FILE, '>', "$dir/file.txt" or return undef;
print FILE 'Example of callback. Arguments: ', join ',', @_;
close FILE
}
Every time you use the get method, it returns only the cache directory where your files are stored. It is up to your code, to do something with these files. Read them, copy them or whatever.
If the cache data are older than expire_sec then the callback subroutine is called automatically; new data are cached, while the old are deleted. So there is no need for a set method.
Write at the callback subroutine the code, that generate new data. Its first argument is always the directory that you should write your cached files. Any optional argument used at the get is passed at the callback
On error get returns FALSE. Sets the error message at the variable $SimpleDir::ERROR and at the property $obj->error_message while the error code is at $obj->error
Generate and return a new cache object, while it initialize/overwrite the default properties
cache_dir The root cache directory of your key
callback The subroutine name that cache new data. Becarefull not it is a simple name not a code reference
expire_sec After how many seconds the record will be considered expired and a new one should cached using the callback
verbose Verbose operation if TRUE or 1
Returns the cache directory where your files/dirs are stored. If the the files/dirs are older than expire_sec seconds then are deleted and new one are cached by calling automatically the subroutine defined at the callback
If your code at the callback encount an error then you must return with FALSE. On success, at the end, your code must return TRUE.
CGI::Cache Perl extension to help cache output of time-intensive CGI scripts
File::Cache Share data between processes via filesystem
Cache::FastMmap Uses an mmap'ed file to act as a shared memory interprocess cache