Cyber Services / All lessons / CentOS / Linux Administration / Scheduling Future Tasks on CentOS 8.5

Scheduling Future Tasks on CentOS 8.5

Module 28 of 33 · 14 min read · Free to read

MODULES ↓ Command blocks have a COPY button

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.

ToolUse CaseExample
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 minutes
  • 14:30 - Today at 2:30 PM
  • tomorrow - Same time tomorrow
  • next week - Same time next week
  • 3:00 PM tomorrow - Specific time tomorrow
  • 2025-12-25 09:00 - Specific date and time

Scheduling a Job for a Specific Time

  1. 1 Install and Start atd Service
    sudo dnf install -y at
    sudo systemctl enable --now atd
    sudo systemctl status atd

    Verify the service is active and running.

  2. 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. 3 Check Scheduled Jobs
    atq

    Lists all pending at jobs with their IDs and execution times.

  4. 4 Cancel a Job (if needed)
    atrm 1

    Replace 1 with the job ID from atq.

  5. 5 View Job Details
    at -c 1

    Shows 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 min

Wait 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 minutes

Part 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 execute

Special 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 as 0 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. 1 Edit Your Personal Crontab
    crontab -e

    💡 First time? It may ask you to choose an editor — pick nano for simplicity.

  2. 2 Add a Recurring Job

    Add this line to run a backup script every day at 3 AM:

    0 3 * * * /home/student/backup-script.sh

    Cron Syntax Explained

    min hour day month weekday command

    • 0 3 * * * = At 03:00 every day
    • */5 * * * * = Every 5 minutes
    • 0 0 * * 0 = Every Sunday at midnight
    • 0 2 1 * * = At 2 AM on the 1st of every month
    • 0 4 * * 1-5 = At 4 AM Monday through Friday
  3. 3 List Your Cron Jobs
    crontab -l
  4. 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.

  1. 5 Create a System Cron Job
    sudo nano /etc/cron.d/system-backup

    Add:

    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/.

  2. 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 -e

Add:

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.sh

Part 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. 1 Create a Service Unit
    sudo nano /etc/systemd/system/mytimer.service

    Add:

    [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. 2 Create a Timer Unit
    sudo nano /etc/systemd/system/mytimer.timer

    Add:

    [Unit]
    Description=Run mytimer.service every 15 minutes
    Requires=mytimer.service
    
    [Timer]
    OnBootSec=5min
    OnUnitActiveSec=15min
    Persistent=true
    
    [Install]
    WantedBy=timers.target

    Timer Options Explained

    • OnBootSec=5min — First run 5 minutes after boot
    • OnUnitActiveSec=15min — Then every 15 minutes
    • Persistent=true — If system was off, run missed jobs at next boot
    • OnCalendar= — For calendar-based scheduling (see advanced examples below)
  3. 3 Enable and Start the Timer
    sudo systemctl daemon-reload
    sudo systemctl enable --now mytimer.timer
    sudo systemctl status mytimer.timer
  4. 4 Check Timer Status
    systemctl list-timers mytimer.timer
    systemctl status mytimer.service
  5. 5 View Logs
    sudo journalctl -u mytimer.service -f

    Follow 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=true

Calendar 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 PM
  • Sun *-*-* 03:00:00 - Every Sunday at 3 AM
  • *-*-1 03:00:00 - 1st of every month at 3 AM
  • Mon..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.target

Then: 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.target

Advanced 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.target

Real-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.target

The 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  Argument

Common Type Codes

  • f - Create a regular file
  • F - Create a regular file with content from argument
  • d - Create a directory
  • D - Create or clean a directory (delete contents older than Age)
  • r - Remove a file or directory if it exists
  • R - Recursively remove a directory and all its contents
  • L - Create a symlink
  • z - Set SELinux context for file/directory

Age Format

Age specifies how old files must be before deletion:

  • 10d - 10 days
  • 2h - 2 hours
  • 30m - 30 minutes
  • 1w - 1 week
  • 1M - 1 month
  • 1y - 1 year

Cleaning /tmp Automatically

  1. 1 View Default tmpfiles Config
    cat /usr/lib/tmpfiles.d/tmp.conf

    You’ll see lines like: D /tmp 1777 root root 10d — delete files older than 10 days.

  2. 2 Create Custom Rule for Another Directory
    sudo nano /etc/tmpfiles.d/myapp.conf

    Add:

    # 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. 3 Test Your Rule Immediately
    sudo systemd-tmpfiles --clean

    💡 Normally runs daily via systemd-tmpfiles-clean.timer.

  4. 4 View All tmpfiles Rules
    systemd-tmpfiles --cat-config

    Shows 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.conf

Add:

D /home/student/uploads 0755 student student 3d

Create 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.conf

Add:

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.conf

Add:

d /var/tmp/secure-app 0700 appuser appuser 1h

This 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 7d

This 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 D to delete files but keep directory, R to delete directory and contents.
  • Age format: 10d = 10 days, 2h = 2 hours, 30m = 30 minutes.
  • Always test with --clean or --create before relying on automatic execution.
  • The systemd-tmpfiles-clean.timer runs 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 ready
  • cron - Handles daily, weekly, and monthly backup schedules
  • at - Schedules one-time validation checks after major deployments
  • tmpfiles - 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/bash and execute permission, verify PATH in cron environment.
  • at job disappeared? → atd service must be running. Check with systemctl status atd. Also check /etc/at.allow and /etc/at.deny.
  • systemd timer not triggering? → Did you run systemctl daemon-reload after creating units? Check systemctl list-timers and service logs.
  • tmpfiles not cleaning? → Run sudo systemd-tmpfiles --clean manually 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 documentation
  • man at - at command documentation
  • man systemd.timer - systemd timer documentation
  • man tmpfiles.d - tmpfiles configuration documentation
  • systemd-analyze calendar "expression" - Test calendar expressions
Modules (33) ← CentOS / Linux Administration