Sample code in PHP checks the size of a folder by path, then deletes all files when the size reaches the limit specified as a percentage of disk space. Create the PHP script located at /path/to/your/script.php
<?php $path = '/path/to/cache_folder'; $limit = 90; // percentage of disk space function get_dir_size($path) { $total_size = 0; $files = scandir($path); foreach($files as $t) { if (is_dir(rtrim($path, '/') . '/' . $t)) { if ($t<>"." && $t<>"..") { $size = get_dir_size(rtrim($path, '/') . '/' . $t); $total_size += $size; } } else { $size = filesize(rtrim($path, '/') . '/' . $t); $total_size += $size; } } return $total_size; } function delete_files($path) { $files = glob($path . '/*'); foreach ($files as $file) { if (is_file($file)) { unlink($file); } elseif (is_dir($file)) { delete_files($file); rmdir($file); } } } $total_space = disk_total_space($path); $free_space = disk_free_space($path); $used_space = $total_space - $free_space; $used_percent = ($used_space / $total_space) * 100; if ($used_percent >= $limit) { $folder_size = get_dir_size($path); if ($folder_size >= $free_space) { delete_files($path); echo 'All files in the folder have been deleted.'; } } ?>
Cron job written in terminal or a command prompt
Create a cron job to check and perform a function every 30 minutes.
To create a cron job that checks and performs a function every 30 minutes, you can use the following steps:
- Open a terminal or a command prompt.
- Type the following command to open the crontab file:
crontab -e
- Add the following line at the end of the file, which specifies a command to run every 30 minutes:
*/30 * * * * /usr/bin/php /path/to/your/script.php
- Save and close the file.
The cron job is now set to run every 30 minutes. The command specified in the crontab file will execute the PHP script located at /path/to/your/script.php
every 30 minutes.
Note: The path to the PHP executable may vary depending on your system. You can use the which php
command to find the path to your PHP executable.
Sample code written in PHP
Here is a sample code written in PHP to create a cron job that checks and performs a function every 30 minutes:
<?php function runTask() { // Your task code goes here echo "Task executed successfully."; } $cronFile = '/etc/cron.d/sample_cron'; $task = "*/30 * * * * root /usr/bin/php " . __FILE__ . " runTask >> /dev/null 2>&1\n"; file_put_contents($cronFile, $task); if (isset($_GET['runTask'])) { runTask(); exit; } ?>
This code creates a new cron job by writing a new entry in the /etc/cron.d/sample_cron
file. The cron job will execute the runTask
function every 30 minutes, as specified in the $task
variable. The output of the task will be redirected to /dev/null
to avoid filling up the file system with logs.