A lightweight Rust utility that automatically cleans directories by removing old files and maintaining size limits.
- Time-based cleanup: Automatically removes files older than a specified threshold
- Size-based cleanup: Maintains directory size under a specified limit by removing oldest files first
- Periodic monitoring: Runs cleanup cycles at configurable intervals
- Minimal logging: Outputs only relevant information about removed files and directory status
The application uses the following constants (defined in src/main.rs):
const CYCLE_DURATION: Duration = Duration::from_secs(30); // How often to check the directory
const MAX_SIZE: u64 = 1024 * 1024 * 100; // Maximum allowed directory size (100 MB)
const LAST_TIME: Duration = Duration::from_secs(60 * 5); // Age threshold for file removal (5 min)
const PATH: &str = "C:/Users/nextr/Music"; // Directory path to monitorModify these constants in the source code according to your needs before building.
- Ensure you have Rust and Cargo installed (Install Rust)
- Clone or download this repository
- Navigate to the project directory
- Build the project:
cargo build --releaseThe executable will be available at target/release/directory_cleaner.
Simply run the executable:
./target/release/directory_cleanerFor Windows:
target\release\directory_cleaner.exeThe program will:
- Create the target directory if it doesn't exist
- Start monitoring the directory based on the configured constants
- Run cleaning cycles at the specified interval
- Print minimal information about each cleaning cycle
-
Every
CYCLE_DURATIONinterval, the program:- Scans the directory and removes files older than
LAST_TIME - Calculates the total size of the directory
- If the total size exceeds
MAX_SIZE, it removes the oldest files until the size is below the limit
- Scans the directory and removes files older than
-
The program uses file modification timestamps to determine file age and removal order
- Files are sorted by modification time to ensure the oldest files are removed first
- The program uses chrono for human-readable timestamp formatting
- All file operations use standard Rust filesystem APIs
- Error handling ensures the program continues running even if individual file operations fail
The code can also be used as a library in other Rust applications:
use directory_cleaner::start_periodically_file_delete;
use std::time::Duration;
fn main() {
let path = "/path/to/directory";
let cycle_duration = Duration::from_secs(300); // 5 minutes
let max_age = Duration::from_secs(86400); // 1 day
let max_size = 1024 * 1024 * 500; // 500 MB
start_periodically_file_delete(path, cycle_duration, max_age, max_size)
.expect("Failed to start directory cleaner");
}This project is open source and available under the MIT License.