Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Cron job to delete file after 24 hours

I read all the related questions and was unable to understand them. I am using Plesk CPanel to set cron job as it was advised by everyone.

I want to delete all files from a folder after 24 hours. Assume that I have to delete it after every 2 mins (So I can check its working or not).

I have two options:

  1. Either run a PHP file that deletes all files after 24 hours using a cron job
  2. Use the cron job command `rm` to delete all the files

I tried both ways and was unable to get my task completed.

Here is the pic of cpanel scheduled task:

http://i41.tinypic.com/2n0tsfs.png

I want to delete files from folder var/www/example.com/public/js/complied. All files inside this complied folder should be deleted. I don't know which to write in Command textfield.

Should I use the following command?

rm /var/www/example.com/public/js/compiled/*.*

Or should I execute a php file?

env php -q/var/www/example.com/public/js/cron.php

The source code of this Cron.php is:

<?php
$dir = "compiled"; // directory name



foreach (scandir($dir) as $item) {
    if ($item == '.' || $item == '..')
        continue;

        unlink($dir.DIRECTORY_SEPARATOR.$item);
        echo "All files deleted";
    }   
//rmdir($dir);

?>

I have tested this code and it works fine.

Thanks in advance.

like image 235
user2290749 Avatar asked Nov 28 '22 11:11

user2290749


2 Answers

I use this in a shell script...

find /some/path -mtime +7 -exec rm {} \; # delete > 7 days old
like image 156
MrCleanX Avatar answered Dec 08 '22 12:12

MrCleanX


To optimize MrCleanX' solution a bit, use xargs:

find /some/path -type f -mtime +7 -print0 | xargs -0 --no-run-if-empty rm

Instead of calling rm for each file to delete, xargs packs many files together to a single call to rm

The -print0 and -0 stuff is to make both find and xargs using NULL terminated strings, which is necessary to handle file names with space and other interesting chars in their names.

like image 40
mogul Avatar answered Dec 08 '22 14:12

mogul