Automate Jobs with at, cron, and systemd Timers — Plus Manage Temporary Files
Want your CentOS system to run tasks automatically — like backups at 2 AM, log cleanup every Sunday, or a script 5 minutes from now? Linux provides powerful tools to schedule jobs: at for one-time tasks, cron for recurring jobs, and modern systemd timers for precision scheduling.
You’ll also learn how to automatically clean up temporary files using systemd-tmpfiles — keeping your system tidy without lifting a finger.
All commands are tested and verified on CentOS 8.5.
Overview: When to Use Which Tool?
The Task Scheduler Analogy
Think of your system as an office. at is like telling your assistant: “Run this report at 3 PM today.” cron is like setting a weekly meeting every Monday at 9 AM. systemd timer is like a smart calendar that can trigger tasks based on boot time, idle time, or complex intervals. And tmpfiles? That’s your janitor — cleaning up spilled coffee (temporary files) every night.
| Tool | Use Case | Example |
|---|---|---|
at |
One-time job at a specific time | “Email me a reminder in 1 hour” |
cron |
Recurring jobs (daily, weekly, etc.) | “Backup database every night at 2 AM” |
systemd timer |
Precise, boot-aware, modern scheduling | “Run cleanup 10 minutes after boot” |
systemd-tmpfiles |
Clean temporary files automatically | “Delete files in /tmp older than 10 days” |
Part 1: Scheduling One-Time Jobs with at
at lets you schedule a command or script to run once at a specific time. It's perfect for delayed execution without keeping a terminal open.
Understanding at Time Syntax
at supports flexible time specifications:
now + 5 minutes- In 5 minutes14:30- Today at 2:30 PMtomorrow- Same time tomorrownext week- Same time next week3:00 PM tomorrow- Specific time tomorrow2025-12-25 09:00- Specific date and time
Scheduling a Job for a Specific Time
- 1 Install and Start
atdServicesudo dnf install -y at sudo systemctl enable --now atd sudo systemctl status atdVerify the service is active and running.
- 2 Schedule a Simple Job
echo "echo 'Hello from at job! $(date)' >> /tmp/at-test.log" | at now + 2 minutes💡 You’ll see output like:
job 1 at Tue Apr 5 14:30:00 2025 - 3 Check Scheduled Jobs
atqLists all pending
atjobs with their IDs and execution times. - 4 Cancel a Job (if needed)
atrm 1Replace
1with the job ID fromatq. - 5 View Job Details
at -c 1Shows the exact commands that will be executed for job ID 1.
Practice Lab 1: Schedule a Reminder Email
Create a script that appends a line to a log file 10 minutes from now:
echo "echo 'REMINDER: Check system logs' >> /home/student/reminders.log" | at now + 10 minWait 10 minutes, then check: cat /home/student/reminders.log
Practice Lab 2: Delayed System Reboot
Schedule a system reboot in 30 minutes (useful for maintenance windows):
echo "sudo /sbin/shutdown -r +0" | at now + 30 minutes⚠️ Warning: Only run this in a test environment! Cancel with atrm [job_id] if needed.
Real-World Scenario: Post-Deployment Validation
After deploying a new application, you need to validate it's running correctly 15 minutes later:
cat > /tmp/validate-app.sh << 'EOF'
#!/bin/bash
if systemctl is-active --quiet myapp; then
echo "$(date): MyApp is running" >> /var/log/deployment-validation.log
else
echo "$(date): MyApp FAILED - restarting" >> /var/log/deployment-validation.log
systemctl restart myapp
fi
EOF
chmod +x /tmp/validate-app.sh
echo "/tmp/validate-app.sh" | at now + 15 minutesPart 2: Scheduling Recurring Jobs with cron
cron is the classic tool for recurring tasks — daily, hourly, or custom intervals. It's reliable, well-understood, and perfect for most automation needs.
Understanding Cron Syntax Deep Dive
Cron uses a 5-field time specification:
# ┌───────────── minute (0 - 59)
# │ ┌──────────── hour (0 - 23)
# │ │ ┌──────────── day of month (1 - 31)
# │ │ │ ┌──────────── month (1 - 12)
# │ │ │ │ ┌──────────── day of week (0 - 6) (Sunday=0 or 7)
# │ │ │ │ │
# │ │ │ │ │
# * * * * * command to executeSpecial Characters and Shortcuts
*- Any value (e.g.,*in minute field = every minute),- Value list separator (e.g.,1,3,5= 1st, 3rd, and 5th)-- Range of values (e.g.,1-5= 1 through 5)/- Step values (e.g.,*/10= every 10 minutes)@reboot- Run at startup@daily- Run once per day at midnight (same as0 0 * * *)@weekly- Run once per week at midnight on Sunday@monthly- Run once per month at midnight on the first day@yearly- Run once per year at midnight on January 1st
Scheduling User Jobs
- 1 Edit Your Personal Crontab
crontab -e💡 First time? It may ask you to choose an editor — pick
nanofor simplicity. - 2 Add a Recurring Job
Add this line to run a backup script every day at 3 AM:
0 3 * * * /home/student/backup-script.shCron Syntax Explained
min hour day month weekday command0 3 * * *= At 03:00 every day*/5 * * * *= Every 5 minutes0 0 * * 0= Every Sunday at midnight0 2 1 * *= At 2 AM on the 1st of every month0 4 * * 1-5= At 4 AM Monday through Friday
- 3 List Your Cron Jobs
crontab -l - 4 Remove All Cron Jobs
crontab -r⚠️ Warning: This deletes all your cron jobs permanently!
Scheduling System-Wide Jobs
System jobs are stored in /etc/crontab or /etc/cron.d/. System crontabs include a user field.
- 5 Create a System Cron Job
sudo nano /etc/cron.d/system-backupAdd:
SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root # Run system backup every day at 4 AM 0 4 * * * root /usr/local/bin/system-backup.sh💡 No need to restart cron — it auto-reloads files in
/etc/cron.d/. - 6 Understand System Cron Directories
CentOS also uses these directories for recurring jobs:
/etc/cron.hourly/- Scripts run hourly/etc/cron.daily/- Scripts run daily (usually around 4 AM)/etc/cron.weekly/- Scripts run weekly (usually Sunday)/etc/cron.monthly/- Scripts run monthly (usually 1st day)
Just place executable scripts in these directories — no cron syntax needed!
Practice Lab 3: Create a Daily Log Rotator
Create a cron job that compresses yesterday’s log every day at 1 AM:
crontab -eAdd:
0 1 * * * gzip -f /var/log/myapp.log.1💡 Assumes your app rotates logs daily (e.g., via logrotate).
Practice Lab 4: Hourly System Monitoring
Create a script that logs system stats every hour:
cat > /home/student/system-monitor.sh << 'EOF'
#!/bin/bash
echo "=== $(date) ===" >> /home/student/system-stats.log
free -h >> /home/student/system-stats.log
df -h >> /home/student/system-stats.log
echo "" >> /home/student/system-stats.log
EOF
chmod +x /home/student/system-monitor.sh
(crontab -l 2>/dev/null; echo "0 * * * * /home/student/system-monitor.sh") | crontab -Advanced Lab: Conditional Cron Jobs
Create a cron job that only runs on weekdays and only if disk usage is above 80%:
cat > /home/student/check-disk.sh << 'EOF'
#!/bin/bash
USAGE=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
if [ $USAGE -gt 80 ]; then
echo "$(date): Disk usage is ${USAGE}%" | mail -s "Disk Alert" admin@example.com
fi
EOF
chmod +x /home/student/check-disk.sh
# Add to crontab: runs every 30 minutes on weekdays only
(crontab -l 2>/dev/null; echo "*/30 * * * 1-5 /home/student/check-disk.sh") | crontab -Real-World Scenario: Database Backup Strategy
Implement a comprehensive backup strategy with daily, weekly, and monthly backups:
# Daily backup at 2 AM
0 2 * * * /usr/local/bin/backup-db.sh daily
# Weekly backup (Sundays at 3 AM)
0 3 * * 0 /usr/local/bin/backup-db.sh weekly
# Monthly backup (1st of month at 4 AM)
0 4 1 * * /usr/local/bin/backup-db.sh monthly
# Clean old backups: keep 7 daily, 4 weekly, 12 monthly
0 5 * * * /usr/local/bin/cleanup-backups.shPart 3: Modern Scheduling with systemd Timers
systemd timers are more precise and powerful than cron — perfect for boot-triggered or complex schedules. They integrate seamlessly with systemd's logging and dependency management.
Why Use systemd Timers Over Cron?
- Precision timing - Can schedule with microsecond accuracy
- Boot awareness - Can trigger based on system boot time
- Dependency management - Can depend on other systemd units
- Better logging - Integrated with journald for easy debugging
- Persistent timers - Can run missed jobs after system comes back online
- Calendar events - Support complex calendar specifications
Creating a Timer + Service Unit
- 1 Create a Service Unit
sudo nano /etc/systemd/system/mytimer.serviceAdd:
[Unit] Description=My Custom Timer Service After=network.target [Service] Type=oneshot User=student ExecStart=/usr/bin/touch /tmp/timer-ran-$(date +%%s).txt StandardOutput=journal StandardError=journal💡 This creates a timestamped file each time it runs. Note the double
%%to escape the percent sign. - 2 Create a Timer Unit
sudo nano /etc/systemd/system/mytimer.timerAdd:
[Unit] Description=Run mytimer.service every 15 minutes Requires=mytimer.service [Timer] OnBootSec=5min OnUnitActiveSec=15min Persistent=true [Install] WantedBy=timers.targetTimer Options Explained
OnBootSec=5min— First run 5 minutes after bootOnUnitActiveSec=15min— Then every 15 minutesPersistent=true— If system was off, run missed jobs at next bootOnCalendar=— For calendar-based scheduling (see advanced examples below)
- 3 Enable and Start the Timer
sudo systemctl daemon-reload sudo systemctl enable --now mytimer.timer sudo systemctl status mytimer.timer - 4 Check Timer Status
systemctl list-timers mytimer.timer systemctl status mytimer.service - 5 View Logs
sudo journalctl -u mytimer.service -fFollow the service logs in real-time.
Advanced Timer Scheduling with Calendar Events
For complex schedules, use OnCalendar= instead of OnBootSec and OnUnitActiveSec:
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=trueCalendar syntax examples:
*-*-* 03:00:00- Every day at 3 AM*-*-* 03:00:00/30- Every 30 minutes starting at 3 AM*-*-* 09..17:00:00- Every hour from 9 AM to 5 PMSun *-*-* 03:00:00- Every Sunday at 3 AM*-*-1 03:00:00- 1st of every month at 3 AMMon..Fri *-*-* 09:00:00- Weekdays at 9 AM
Practice Lab 5: Create a Boot Cleanup Timer
Create a timer that deletes files from /tmp/old/ 2 minutes after boot:
# Service: /etc/systemd/system/cleanup-old.service
[Unit]
Description=Clean old temp files
After=local-fs.target
[Service]
Type=oneshot
ExecStart=/usr/bin/find /tmp/old -type f -delete
RemainAfterExit=yes# Timer: /etc/systemd/system/cleanup-old.timer
[Unit]
Description=Run cleanup 2 min after boot
[Timer]
OnBootSec=2min
[Install]
WantedBy=timers.targetThen: sudo systemctl enable --now cleanup-old.timer
Practice Lab 6: Daily Report Timer
Create a systemd timer that generates a daily system report at 6 AM:
# Service: /etc/systemd/system/daily-report.service
[Unit]
Description=Generate daily system report
[Service]
Type=oneshot
ExecStart=/usr/local/bin/generate-report.sh
User=student# Timer: /etc/systemd/system/daily-report.timer
[Unit]
Description=Run daily report at 6 AM
[Timer]
OnCalendar=*-*-* 06:00:00
Persistent=true
[Install]
WantedBy=timers.targetAdvanced Lab: Conditional Timer with Dependencies
Create a timer that only runs after the network is available and a specific service is running:
# Service: /etc/systemd/system/conditional-task.service
[Unit]
Description=Conditional task that requires network and database
After=network-online.target mariadb.service
Wants=network-online.target mariadb.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/conditional-script.sh
User=appuser# Timer: /etc/systemd/system/conditional-task.timer
[Unit]
Description=Run conditional task every hour
[Timer]
OnCalendar=*-*-* *:00:00
Persistent=true
[Install]
WantedBy=timers.targetReal-World Scenario: Application Health Check
Implement a health check that runs every 5 minutes and restarts the application if it's not responding:
# Service: /etc/systemd/system/app-healthcheck.service
[Unit]
Description=Application Health Check
After=myapp.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/check-app-health.sh
User=appuser# Timer: /etc/systemd/system/app-healthcheck.timer
[Unit]
Description=Run health check every 5 minutes
[Timer]
OnCalendar=*-*-* *:00/5:00
Persistent=true
[Install]
WantedBy=timers.targetThe health check script would use curl or similar to test the application endpoint.
Part 4: Managing Temporary Files with systemd-tmpfiles
Keep your system clean by automatically purging old temporary files. This is essential for maintaining disk space and security.
Understanding tmpfiles Configuration
tmpfiles uses configuration files with the following format:
Type Path Mode UID GID Age ArgumentCommon Type Codes
f- Create a regular fileF- Create a regular file with content from argumentd- Create a directoryD- Create or clean a directory (delete contents older than Age)r- Remove a file or directory if it existsR- Recursively remove a directory and all its contentsL- Create a symlinkz- Set SELinux context for file/directory
Age Format
Age specifies how old files must be before deletion:
10d- 10 days2h- 2 hours30m- 30 minutes1w- 1 week1M- 1 month1y- 1 year
Cleaning /tmp Automatically
- 1 View Default tmpfiles Config
cat /usr/lib/tmpfiles.d/tmp.confYou’ll see lines like:
D /tmp 1777 root root 10d— delete files older than 10 days. - 2 Create Custom Rule for Another Directory
sudo nano /etc/tmpfiles.d/myapp.confAdd:
# Type Path Mode User Group Age Argument D /var/tmp/myapp 0755 root root 7d💡
D= delete files older than 7 days, but keep directory. - 3 Test Your Rule Immediately
sudo systemd-tmpfiles --clean💡 Normally runs daily via
systemd-tmpfiles-clean.timer. - 4 View All tmpfiles Rules
systemd-tmpfiles --cat-configShows all active tmpfiles configuration from all directories.
Practice Lab 7: Auto-Clean Student Uploads
Create a rule to delete files older than 3 days from /home/student/uploads/:
sudo mkdir -p /home/student/uploads
sudo nano /etc/tmpfiles.d/student-uploads.confAdd:
D /home/student/uploads 0755 student student 3dCreate a test file: touch /home/student/uploads/oldfile.txt
Wait 3 days — or manually test: sudo systemd-tmpfiles --clean
Practice Lab 8: Create Required Directories at Boot
Create a rule that ensures application directories exist at boot:
sudo nano /etc/tmpfiles.d/myapp-dirs.confAdd:
d /var/log/myapp 0755 myapp myapp -
d /var/run/myapp 0755 myapp myapp -
f /var/log/myapp/app.log 0644 myapp myapp -Apply immediately: sudo systemd-tmpfiles --create
Advanced Lab: Secure Temporary Directory
Create a secure temporary directory that's only accessible to a specific user and cleaned hourly:
sudo nano /etc/tmpfiles.d/secure-tmp.confAdd:
d /var/tmp/secure-app 0700 appuser appuser 1hThis creates a directory that's only readable/writable by appuser and cleans files older than 1 hour.
Real-World Scenario: Web Application Cache Cleanup
Implement cache cleanup for a web application that stores temporary files:
# /etc/tmpfiles.d/webapp-cache.conf
D /var/www/html/cache 0755 apache apache 2h
D /var/www/html/sessions 0755 apache apache 24h
D /var/www/html/uploads 0755 apache apache 7dThis ensures cache files are cleaned every 2 hours, sessions after 24 hours, and uploads after 7 days.
⚠️ Important Notes
- Rules in
/etc/tmpfiles.d/override those in/usr/lib/. - Use
Dto delete files but keep directory,Rto delete directory and contents. - Age format:
10d= 10 days,2h= 2 hours,30m= 30 minutes. - Always test with
--cleanor--createbefore relying on automatic execution. - The
systemd-tmpfiles-clean.timerruns daily by default.
Part 5: Advanced Integration and Best Practices
Combining Tools for Complex Workflows
Real-world scenarios often require combining multiple scheduling tools:
Integrated Backup System
Implement a comprehensive backup system using all three tools:
systemd timer- Runs immediately after boot to ensure backup service is readycron- Handles daily, weekly, and monthly backup schedulesat- Schedules one-time validation checks after major deploymentstmpfiles- Cleans old backup files automatically
Security Best Practices
- Minimize privileges - Always run jobs with the least privilege necessary
- Validate input - Never trust data from scheduled jobs without validation
- Secure scripts - Ensure script files have proper permissions (600 or 700)
- Audit regularly - Review all scheduled jobs monthly for security
- Log everything - Ensure all jobs produce meaningful logs for auditing
Performance Considerations
- Avoid overlapping jobs - Use locking mechanisms for long-running jobs
- Stagger execution - Don't schedule all jobs at the same time (e.g., avoid 0 0 * * *)
- Monitor resource usage - Use systemd's resource limits for memory/CPU intensive jobs
- Use efficient commands - Optimize scripts to minimize system impact
Quick Reference & Troubleshooting
🔧 Common Issues & Fixes
- Cron job not running? → Check
systemctl status crond, ensure script has#!/bin/bashand execute permission, verify PATH in cron environment. - at job disappeared? →
atdservice must be running. Check withsystemctl status atd. Also check/etc/at.allowand/etc/at.deny. - systemd timer not triggering? → Did you run
systemctl daemon-reloadafter creating units? Checksystemctl list-timersand service logs. - tmpfiles not cleaning? → Run
sudo systemd-tmpfiles --cleanmanually to test. Check syntax in .conf file and file permissions. - Environment variables missing? → Cron and at have minimal environments. Always use full paths and set required variables explicitly.
- Special characters not working? → Escape percent signs in cron (
%%) and use single quotes to prevent shell expansion.
📌 Comprehensive Cheat Sheet
# AT
at now + 1 hour # Schedule job
atq # List jobs
atrm # Delete job
at -c # View job details
echo "command" | at 14:30 # Schedule specific time
# CRON
crontab -e # Edit user cron
crontab -l # List user cron
crontab -r # Remove all user cron jobs
sudo nano /etc/cron.d/ # System cron
sudo systemctl status crond # Check cron service
# SYSTEMD TIMER
systemctl list-timers # List all timers
systemctl status # Check timer status
sudo journalctl -u -f # Follow service logs
systemctl daemon-reload # Reload after unit changes
# TMPFILES
sudo systemd-tmpfiles --clean # Run cleanup now
sudo systemd-tmpfiles --create # Create directories/files now
systemd-tmpfiles --cat-config # View all config
man tmpfiles.d # View syntax manual
man systemd.time # View calendar syntax 📚 Additional Resources
man 5 crontab- Cron file format documentationman at- at command documentationman systemd.timer- systemd timer documentationman tmpfiles.d- tmpfiles configuration documentationsystemd-analyze calendar "expression"- Test calendar expressions