Automating File Cleanup and Cron Jobs on Linux: A Complete Step-by-Step Guide


Web applications regularly generate temporary files, logs, and session data. Over time, these files accumulate and can overwhelm the server, causing:

  • Slower performance
  • Application errors
  • Disk exhaustion
  • Unexpected crashes

To maintain a healthy server environment, it’s essential to automate tasks such as deleting old files, running scheduled cleanup jobs, and executing routine maintenance commands.
This guide provides a complete walkthrough of identifying file locations, setting up automated cleanup using systemd timers, and scheduling URL or command-based tasks using cron jobs.


πŸ“‚ 1. Identify the Directory That Needs Automatic Cleanup

Most PHP-based or custom applications generate session files in paths similar to:

/path/to/project/src/var/sessions

First, verify the directory exists:

ls -l /path/to/project/src/var/sessions

If you see files like:

sess_abcd1234
sess_xyz890

β€”then this is the correct directory to clean.


πŸ§ͺ 2. Test File Removal (Without Deleting Anything Yet)

Before deleting files, list which files would be removed.
To list files older than 20 hours:

find /path/to/project/src/var/sessions -type f -mmin +1200 -print

This safely shows all files older than 20 hours without removing them.

Use this list to confirm you’re targeting the correct directory.


πŸ—‘οΈ 3. Create a Systemd Service to Delete Old Files Automatically

Systemd services allow you to automate tasks in a robust and secure way.

Create the service file:

sudo nano /etc/systemd/system/session-cleaner.service

Paste the following:

[Unit]
Description=Automatically delete old session/log files

[Service]
Type=oneshot
ExecStart=/usr/bin/find /path/to/project/src/var/sessions -type f -mmin +1200 -delete

Explanation:

  • -mmin +1200 β†’ delete files older than 20 hours
  • Adjust to:
    • 1 day: +1440
    • 2 days: +2880

Save and exit.


⏲️ 4. Create a Systemd Timer to Run Cleanup on a Schedule

Now create the timer that will run this service automatically:

sudo nano /etc/systemd/system/session-cleaner.timer

Paste:

[Unit]
Description=Run session cleaner at regular intervals

[Timer]
OnBootSec=30min
OnUnitActiveSec=12h
Unit=session-cleaner.service

[Install]
WantedBy=timers.target

This will:

  • Run 30 minutes after boot
  • Then run every 12 hours

Activate the timer:

sudo systemctl daemon-reload
sudo systemctl enable --now session-cleaner.timer

Verify:

systemctl status session-cleaner.timer

🧹 5. Test the Cleanup Service Manually

Before relying on the timer, test the service once:

sudo systemctl start session-cleaner.service

Verify cleanup:

ls -l /path/to/project/src/var/sessions

Old files will be removed.


πŸ”„ 6. Adding a Cron Job to Run a URL or Script Automatically

Many web applications require scheduled tasks such as:

  • Running background processing
  • Triggering API calls
  • Executing maintenance scripts

If your application exposes a task runner as a URL, for example:

https://yourdomain.com/runtasks?token=YOUR_TOKEN_HERE

You can run it using a cron job.

Open crontab:

crontab -e

Add this entry to run every 15 minutes:

*/15 * * * * /usr/bin/wget -q -O /dev/null "https://yourdomain.com/runtasks?token=YOUR_TOKEN_HERE"

βœ” What this does:

  • Runs every 15 minutes
  • Silences output (-q)
  • Prevents log files (-O /dev/null)
  • Safely executes the task URL

βœ” Recommended for environments like CloudPanel

Run cron under the website’s user:

sudo -u youruser crontab -e

Paste the same cron entry.


⚑ 7. Systemd Timer vs Cron Jobs β€” Which Should You Use?

FeatureCronSystemd Timer
PrecisionModerateVery accurate
Run on bootNoYes
LoggingMinimalDetailed
ReliabilityGoodExcellent
Best useURL triggers, simple tasksFile cleanup, maintenance tasks

Use systemd timers for cleanup tasks.
Use cron jobs for URL-based or script-based automation.


πŸ” 8. Protecting Sensitive Information in Automation

When automating tasks, always protect:

  • API keys
  • Tokens in URLs
  • Database credentials
  • Access scripts
  • Config files

Recommended Practices:

βœ” Use HTTPS for all task URLs
βœ” Keep tokens long, random, and confidential
βœ” Avoid output logs using -q -O /dev/null
βœ” Restrict access to systemd and cron files
βœ” Make sure only the application user can access sensitive directories


πŸŽ‰ Conclusion

Automating file cleanup and task scheduling is essential for maintaining a healthy, stable, and secure web server. By properly configuring systemd services, systemd timers, and cron jobs, you ensure:

  • Clean session and log directories
  • Optimal disk usage
  • Reliable recurring tasks
  • Reduced risk of server slowdowns or crashes

This guide gives you everything you need to implement a production-ready, automated maintenance system on any Linux or CloudPanel-based server.