Scheduling Tasks with cron and at

Task scheduling is fundamental to Linux system administration and automation. Whether you need to run regular maintenance jobs, schedule one-time tasks, or automate complex workflows, understanding cron and at commands is essential. This comprehensive guide covers everything from basic scheduling to advanced automation techniques.

cron vs at: Key Differences

Aspect cron at
Type Recurring tasks One-time tasks
Schedule Regular intervals Specific time once
Configuration crontab files at command
Persistence Survives reboot Lost on reboot*
Complexity Time patterns Simple time specs
Use Case Backups, reports, maintenance Reminders, delayed jobs
Quick Reference:
cron - For recurring tasks (daily, weekly, monthly)
at - For one-time tasks at specific times
crontab -e - Edit user's cron jobs
crontab -l - List cron jobs
at now + 1 hour - Schedule job in 1 hour
atq - List pending at jobs
atrm - Remove at job

cron Scheduling Workflow

Complete cron Job Management

crontab -e
Edit Schedule
Save & Exit
cron daemon
Execute Job

cron Syntax and Special Characters

Field Values Special Characters Examples
Minute 0-59 , - * / 0,15,30,45 or */15
Hour 0-23 , - * / 0,12 or 9-17
Day of Month 1-31 , - * / ? L W 1,15 or L (last day)
Month 1-12 or JAN-DEC , - * / 1,6,12 or JAN,JUN,DEC
Day of Week 0-7 or SUN-SAT , - * / ? L # 1-5 or MON-FRI

Special Character Meanings

*
- Any value
,
- Value list separator
-
- Range of values
/
- Step values
?
- No specific value (cron)
L
- Last day of month/week
W
- Nearest weekday
#
- Nth day of month

Essential cron and at Commands

crontab

Maintain crontab files for individual users.

crontab [options] [file]

Common Options:

  • crontab -e - Edit crontab
  • crontab -l - List crontab
  • crontab -r - Remove crontab
  • crontab -u user - Specify user (root only)

File Locations:

  • /var/spool/cron/ - User crontabs
  • /etc/crontab - System crontab
  • /etc/cron.d/ - Package crontabs
📅
at

Schedule one-time tasks for execution.

at [options] time

Time Formats:

  • at now + 1 hour
  • at 14:30
  • at 2:30 PM tomorrow
  • at noon next week

Interactive Usage:

$ at now + 5 minutes
at> echo "Hello" > /tmp/reminder
at> Ctrl+D
job 1 at Thu Dec  2 10:05:00 2025
📋
atq & atrm

Manage pending at jobs.

atq [options] | atrm job_id

Job Management:

  • atq - List pending jobs
  • atrm 1 - Remove job 1
  • atq -c - List with details
  • at -l - Alias for atq

File Locations:

  • /var/spool/at/ - Pending jobs
  • /var/spool/at/spool - Job files

cron Time Specification Examples

Schedule cron Expression Description
Every minute * * * * * Run every minute
Every hour 0 * * * * At minute 0 of every hour
Daily 0 2 * * * 2:00 AM every day
Weekly 0 2 * * 0 2:00 AM every Sunday
Monthly 0 2 1 * * 2:00 AM on 1st of month
Every 15 minutes */15 * * * * 0,15,30,45 minutes
Work hours 0 9-17 * * 1-5 9AM-5PM on weekdays
Twice daily 0 9,17 * * * 9AM and 5PM daily

System cron Directories

📁

/etc/cron.d/

Directory for package-specific cron jobs.

Files in /etc/cron.d/

Features:

  • Package managers can drop files here
  • Same syntax as crontab
  • Includes user field in format
  • Easy to manage and backup

Example File:

# /etc/cron.d/backup
0 2 * * * root /usr/local/bin/backup.sh
🕒

/etc/cron.hourly/daily/weekly/monthly

Anacron-style directories for periodic jobs.

Scripts in periodic directories

Usage:

  • Place executable scripts in directories
  • Run by run-parts command
  • No complex cron syntax needed
  • Ideal for system maintenance

Example:

# Script in /etc/cron.daily/
#!/bin/bash
/usr/bin/updatedb
👑

/etc/crontab

System-wide crontab file.

System crontab format

Format:

  • Includes user field: min hour dom mon dow user command
  • Managed by system administrator
  • Used for system-level jobs
  • Requires root privileges to edit

Example Entry:

# /etc/crontab
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly

Practical Scheduling Examples

Real-World cron and at Job Scenarios

# 1. Basic cron Job Management
# Edit user's crontab
crontab -e

# List current jobs
crontab -l

# Remove all jobs
crontab -r

# 2. Common cron Job Examples
# Backup every day at 2 AM
0 2 * * * /home/user/scripts/backup.sh

# Clean temp files every Sunday at 3 AM
0 3 * * 0 /home/user/scripts/cleanup.sh

# Monitor disk space every hour during work hours
0 9-17 * * 1-5 /home/user/scripts/disk_check.sh

# Update package list every day at 6 AM
0 6 * * * /usr/bin/apt update

# Sync important files every 30 minutes
*/30 * * * * /usr/bin/rsync -av /important/ /backup/

# 3. Advanced cron Patterns
# Every 10 minutes during business hours
*/10 9-17 * * 1-5 /home/user/scripts/monitor.sh

# First day of every month at midnight
0 0 1 * * /home/user/scripts/monthly_report.sh

# Every weekday at 6 PM
0 18 * * 1-5 /home/user/scripts/end_of_day.sh

# Every 2 hours from 8 AM to 8 PM
0 8-20/2 * * * /home/user/scripts/check_service.sh

# Last day of month at 11 PM
0 23 28-31 * * [ $(date -d tomorrow +\%d) -eq 1 ] && /home/user/scripts/end_of_month.sh

# 4. at Command Examples
# Schedule job in 5 minutes
echo "echo 'Task completed' > /tmp/done.txt" | at now + 5 minutes

# Schedule job at specific time
at 14:30
at> /home/user/scripts/meeting_reminder.sh
at> Ctrl+D

# Schedule complex command
at tomorrow 9:00 AM
at> cd /home/user/project && ./build.sh
at> ./deploy.sh
at> Ctrl+D

# 5. System cron Examples
# System-wide backup (in /etc/crontab)
0 1 * * * root /usr/local/bin/full_backup.sh

# Log rotation (in /etc/cron.d/logrotate)
0 0 * * * root /usr/sbin/logrotate /etc/logrotate.conf

# System updates (in /etc/cron.d/updates)
0 4 * * 0 root /usr/bin/apt update && /usr/bin/apt upgrade -y

# 6. Error Handling and Logging
# Redirect output to log file
0 2 * * * /home/user/scripts/backup.sh > /var/log/backup.log 2>&1

# Send output via email (default)
0 3 * * * /home/user/scripts/report.sh

# Silent execution (discard output)
0 4 * * * /home/user/scripts/cleanup.sh > /dev/null 2>&1

# 7. Environment Variables in cron
# Set PATH at top of crontab
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# Set specific variables
MAILTO=admin@example.com
0 5 * * * /home/user/scripts/daily_task.sh

# 8. Conditional Execution
# Run only if file exists
0 6 * * * [ -f /tmp/trigger ] && /home/user/scripts/process.sh

# Run only on specific hostname
0 7 * * * [ $(hostname) = "server1" ] && /home/user/scripts/server1_task.sh

# 9. Complex Workflows
# Chain multiple commands
0 8 * * * /home/user/scripts/step1.sh && /home/user/scripts/step2.sh

# Use wrapper script for complex logic
0 9 * * * /home/user/scripts/daily_workflow.sh

# 10. Monitoring and Maintenance
# Check if cron is running
*/5 * * * * /home/user/scripts/check_cron.sh

# Rotate cron logs
0 0 * * 0 /home/user/scripts/rotate_cron_logs.sh

# Alert on cron failures
0 * * * * /home/user/scripts/monitor_cron_jobs.sh

Common Use Cases

System Administration

  • Backup Operations: 0 2 * * * /backup/script.sh
  • Log Management: 0 0 * * * /usr/sbin/logrotate
  • System Updates: 0 4 * * 0 apt update && apt upgrade -y
  • Monitoring: */5 * * * * /monitoring/check_system.sh

Development & Deployment

  • Build Processes: 0 6 * * 1-5 /build/nightly.sh
  • Database Maintenance: 0 3 * * * /scripts/db_optimize.sh
  • Cache Clearing: 0 1 * * * /app/clear_cache.sh
  • Deployment: at 02:00 tomorrow for off-hours deployment

Business Operations

  • Report Generation: 0 8 * * 1-5 /reports/daily.sh
  • Data Sync: */15 9-17 * * 1-5 /sync/data.sh
  • Batch Processing: 0 22 * * * /processing/nightly_batch.sh
  • Reminders: at 09:00 tomorrow for meeting reminders

Advanced Scheduling Techniques

🛡️

Security Considerations

Secure your scheduled tasks properly.

/etc/cron.allow | /etc/cron.deny

Access Control:

  • /etc/cron.allow - Allow listed users only
  • /etc/cron.deny - Deny listed users
  • Empty deny file allows all users
  • Root always has access

Best Practices:

  • Use full paths in commands
  • Set appropriate permissions
  • Limit cron access to trusted users
  • Monitor cron log files
📧

Email Notifications

Configure output and error notifications.

MAILTO=user@example.com

Configuration:

  • Set MAILTO in crontab
  • Output is emailed to MAILTO
  • Empty MAILTO discards output
  • Use >/dev/null 2>&1 to suppress

Examples:

MAILTO=admin@example.com
0 2 * * * /scripts/backup.sh

MAILTO=""
0 3 * * * /scripts/cleanup.sh >/dev/null 2>&1
🔧

Debugging cron Jobs

Troubleshoot and monitor cron execution.

Log analysis & testing

Debugging Steps:

  • Check /var/log/syslog or /var/log/cron
  • Test commands manually first
  • Use full paths in scripts
  • Check environment variables
  • Verify file permissions

Testing:

# Test command manually
/usr/local/bin/myscript.sh

# Check cron logs
grep CRON /var/log/syslog

# Verify environment
env -i /bin/bash -c "/usr/local/bin/myscript.sh"
Important Considerations:
• cron jobs run with minimal environment - set PATH and other variables explicitly
• Use full paths to commands and files in cron jobs
• at jobs are lost on system reboot unless atd is configured to save them
• Test cron jobs thoroughly before deployment
• Monitor cron job execution and log files regularly
• Be cautious with jobs that run as root
• Consider using flock to prevent overlapping job execution
• Always handle errors and timeouts in scheduled scripts
Pro Tips:
• Use flock to prevent multiple instances of the same job
• Set MAILTO for important job notifications
• Use #!/bin/bash shebang in scripts for consistency
• Test cron syntax with online validators
• Use sudo crontab -u user -e to edit other users' crontabs
• Consider anacron for jobs on systems that aren't always on
• Use timeout command to prevent hanging jobs
• Implement proper logging in all scheduled scripts

Key Takeaways

Mastering cron and at scheduling transforms system administration from manual intervention to automated efficiency. By understanding cron's powerful time specification syntax and at's simplicity for one-time tasks, you can automate virtually any repetitive system task. Remember that proper job scheduling involves not just setting up the timing, but also implementing robust error handling, logging, and monitoring. Whether you're managing simple daily backups or complex multi-step workflows, these scheduling tools provide the foundation for reliable, hands-off system operation. The key to successful automation is thorough testing, comprehensive logging, and continuous monitoring to ensure your scheduled tasks perform as expected.

Next Step: Explore advanced automation with systemd timers and anacron for more sophisticated scheduling scenarios and systems that don't run 24/7.