|
|
OverviewDelete old temporary files automatically. When this script is executed, temporary files generated before will be deleted if the time past the specified time.
Flow
A sample code
my $prefix = 'tmp_';
opendir(TMPDIR, "$tmpdir");
my @tmplist = grep /^$prefix.*\.tmp$/, readdir TMPDIR;
closedir(TMPDIR);
my $expire = 60;
my $now = time;
foreach my $tmpfile (@tmplist){
my $mtime = (stat("$tmpdir/$tmpfile"))[9];
if ($now > $mtime + $expire * 60){
unlink("$tmpdir/$tmpfile");
}
}
Description of the codemy $prefix = 'tmp_'; Assuming temporary files have the prefix tmp_. Just for convenience, put it into $prefix. opendir(TMPDIR, "$tmpdir"); my @tmplist = grep /^$prefix.*\.tmp$/, readdir TMPDIR; closedir(TMPDIR); Open $tmpdir and extract tmp_*.tmp in that directory and put them into @tmplist. my $expire = 60; Set expiration time. Where 60 minutes is specified. my $now = time; Get current time.
foreach my $tmpfile (@tmplist){
my $mtime = (stat("$tmpdir/$tmpfile"))[9];
if ($now > $mtime + $expire * 60){
unlink("$tmpdir/$tmpfile");
}
}
Check time time of the files in @tmplist one by one. If it exceed 60 minutes, delete it.
my $mtime = (stat("$tmpdir/$tmpfile"))[9];
Get the updated time of the file.
if ($now > $mtime + $expire * 60){
If $now is $mtime + $expire * 60, it means the file past more than 60 minutes. So delete it in if block. If not, do nothing.
unlink("$tmpdir/$tmpfile");
Delete using unlink. |