In this lesson, you will learn how to design robust, self-maintaining storage routines using systemd timers to prevent disk bloat and filesystem degradation.
Designing Storage Maintenance Routines
While basic cron jobs are common, intermediate Linux administration requires the precision of systemd timers for storage housekeeping. When dealing with periodic tasks—such as clearing caches, purging old backups, or running filesystem integrity checks—you need a two-part orchestration: a service unit that executes the logic and a timer unit that governs the schedule.
The key to effective housekeeping is ensuring that tasks are idempotent and fail-safe. Instead of a simple rm, your service script should use logic to verify the target directory exists and check that the disk isn't already under high I/O pressure.
Example: Implementing a Daily Cleanup
To clean up a specific application log directory safely, create housekeep-logs.service:
[Unit]
Description=Daily cleanup of archived application logs
[Service]
Type=oneshot
ExecStart=/usr/bin/find /var/log/myapp/archived -type f -mtime +30 -delete
Nice=19
IOSchedulingClass=idle
By setting IOSchedulingClass=idle and Nice=19, we ensure that our housekeeping task does not compete for resources with critical system processes.
Next, pair this with housekeep-logs.timer:
[Unit]
Description=Timer for daily log cleanup
[Timer]
OnCalendar=daily
Persistent=true
RandomizedDelaySec=3600
[Install]
WantedBy=timers.target
Using Persistent=true ensures that if the system was powered off when the task was scheduled, the task will run immediately upon boot. The RandomizedDelaySec is a critical professional touch; it prevents a "thundering herd" effect where multiple servers or services trigger storage-intensive tasks at the exact same second, potentially causing IOPS spikes or backup bottlenecks.
By decoupling the cleanup logic from the schedule, you create a modular maintenance pipeline that is observable via systemctl list-timers and easy to audit within your infrastructure-as-code repository.
Key Takeaway: Effective periodic housekeeping relies on combining low-priority service execution with persistent, randomized timers to ensure system health without compromising performance during peak hours.