Complete Guide to Linux at Command: Schedule One-Time Jobs

Master the Linux at command for scheduling one-time tasks. Learn syntax, time formats, job management, and best practices with practical examples.

Complete Guide to the at Command in Linux

Table of Contents

1. [Introduction](#introduction) 2. [Installation and Setup](#installation-and-setup) 3. [Basic Syntax](#basic-syntax) 4. [Time Specification Formats](#time-specification-formats) 5. [Command Examples](#command-examples) 6. [Managing Scheduled Jobs](#managing-scheduled-jobs) 7. [Configuration Files](#configuration-files) 8. [Access Control](#access-control) 9. [Advanced Usage](#advanced-usage) 10. [Troubleshooting](#troubleshooting) 11. [Comparison with Other Scheduling Tools](#comparison-with-other-scheduling-tools) 12. [Best Practices](#best-practices)

Introduction

The at command is a Linux utility that allows users to schedule commands or scripts to run at a specific time in the future. Unlike cron, which is designed for recurring tasks, at is specifically designed for one-time job execution. The at daemon (atd) must be running on the system for scheduled jobs to execute properly.

Key Features

- Schedule one-time execution of commands - Flexible time specification formats - Job queue management - Access control mechanisms - Integration with system mail for output handling

How It Works

When you schedule a job with at, the command creates a job file in the /var/spool/at directory. The atd daemon continuously monitors this directory and executes jobs when their scheduled time arrives. The output of executed jobs is typically sent to the user via email unless redirected.

Installation and Setup

Checking Installation Status

Most Linux distributions include the at package by default. To verify if at is installed:

`bash which at at --version `

Installing at Package

#### Ubuntu/Debian Systems `bash sudo apt update sudo apt install at `

#### Red Hat/CentOS/Fedora Systems `bash

For RHEL/CentOS 7 and older

sudo yum install at

For RHEL/CentOS 8+ and Fedora

sudo dnf install at `

#### Arch Linux `bash sudo pacman -S at `

Starting and Enabling the atd Service

After installation, ensure the atd daemon is running:

`bash

Start the service

sudo systemctl start atd

Enable automatic startup

sudo systemctl enable atd

Check service status

sudo systemctl status atd `

For systems using SysV init: `bash sudo service atd start sudo chkconfig atd on `

Basic Syntax

The basic syntax of the at command is:

`bash at [options] time `

Common Options

| Option | Description | |--------|-------------| | -f file | Read commands from a file instead of standard input | | -m | Send mail to user when job completes, even if no output | | -M | Never send mail to user | | -q queue | Use specified queue (a-z, A-Z) | | -l | List pending jobs (equivalent to atq) | | -d job_id | Delete specified job (equivalent to atrm) | | -v | Show the time job will be executed | | -c job_id | Display the contents of a job |

Time Specification Formats

The at command accepts various time formats, making it flexible for different scheduling needs.

Absolute Time Formats

| Format | Example | Description | |--------|---------|-------------| | HH:MM | 14:30 | 24-hour format | | HH:MM AM/PM | 2:30 PM | 12-hour format | | HH:MM:SS | 14:30:45 | With seconds | | MMDDYY | 123121 | December 31, 2021 | | MM/DD/YY | 12/31/21 | Date with slashes | | DD.MM.YY | 31.12.21 | European format | | YYYY-MM-DD | 2021-12-31 | ISO format |

Relative Time Formats

| Format | Example | Description | |--------|---------|-------------| | now + time | now + 5 minutes | Relative to current time | | today | today | Today at current time | | tomorrow | tomorrow | Tomorrow at current time | | teatime | teatime | 4:00 PM today | | noon | noon | 12:00 PM today | | midnight | midnight | 12:00 AM today |

Time Units for Relative Scheduling

| Unit | Singular | Plural | Abbreviation | |------|----------|--------|--------------| | Minute | minute | minutes | min | | Hour | hour | hours | hr | | Day | day | days | - | | Week | week | weeks | - | | Month | month | months | - | | Year | year | years | - |

Command Examples

Basic Job Scheduling

#### Schedule a Simple Command `bash at 15:30 at> echo "Meeting reminder" | mail user@example.com at> ` Press Ctrl+D to finish input.

#### Using Echo with Pipe `bash echo "ls -la /home" | at now + 1 hour `

#### Schedule with File Input `bash at -f /path/to/script.sh tomorrow `

Practical Examples

#### System Maintenance Tasks `bash

Schedule system update

echo "sudo apt update && sudo apt upgrade -y" | at 2:00 AM tomorrow

Schedule log cleanup

echo "find /var/log -name '*.log' -mtime +30 -delete" | at midnight `

#### Backup Operations `bash

Schedule database backup

at 23:00 << EOF mysqldump -u root -p database_name > /backup/db_backup_$(date +%Y%m%d).sql EOF `

#### File Operations `bash

Schedule file compression

echo "tar -czf /backup/documents_$(date +%Y%m%d).tar.gz /home/user/documents" | at now + 30 minutes `

#### Network Operations `bash

Schedule network connectivity test

at 09:00 << EOF ping -c 5 google.com > /tmp/network_test_$(date +%Y%m%d_%H%M).log 2>&1 EOF `

Advanced Scheduling Examples

#### Using Different Queues `bash

High priority queue (a)

echo "important_task.sh" | at -q a now + 1 hour

Low priority queue (z)

echo "background_task.sh" | at -q z midnight `

#### Complex Time Specifications `bash

Schedule for specific date and time

echo "monthly_report.sh" | at 09:00 AM Dec 1, 2024

Schedule for next Friday

echo "weekly_cleanup.sh" | at 18:00 next Friday

Schedule for teatime (4 PM)

echo "afternoon_task.sh" | at teatime tomorrow `

Managing Scheduled Jobs

Viewing Scheduled Jobs

#### List All Jobs `bash atq

or

at -l `

Output format: ` 23 Tue Dec 5 14:30:00 2023 a username 24 Wed Dec 6 09:00:00 2023 a username `

#### Detailed Job Information `bash

View job contents

at -c 23

View job with verbose timing

at -v 23 `

Removing Scheduled Jobs

#### Remove Specific Job `bash atrm 23

or

at -d 23 `

#### Remove Multiple Jobs `bash atrm 23 24 25 `

#### Remove All Jobs for Current User `bash for job in $(atq | awk '{print $1}'); do atrm $job; done `

Job Status and Monitoring

#### Check Job Execution History `bash

Check system logs

sudo journalctl -u atd

Check mail for job output

mail `

#### Monitor atd Service `bash

Service status

systemctl status atd

Service logs

journalctl -u atd -f `

Configuration Files

Main Configuration Files

| File | Purpose | |------|---------| | /etc/at.allow | Users allowed to use at command | | /etc/at.deny | Users denied access to at command | | /var/spool/at/ | Directory containing job files | | /var/spool/at/spool/ | Queued jobs | | /etc/default/atd | Default configuration for atd daemon |

atd Configuration

#### /etc/default/atd `bash

Options for atd daemon

OPTIONS="-l 1.5" # Load average limit `

#### Common atd Options

| Option | Description | |--------|-------------| | -l load_avg | Set maximum load average | | -b batch_interval | Set batch queue check interval | | -d | Debug mode | | -s | Process job queue only once |

Job File Location and Structure

Jobs are stored in /var/spool/at/ with the following structure: ` /var/spool/at/ ├── a00001015f4a2b # Job file (queue + job number + timestamp) ├── spool/ # Queued jobs directory └── past/ # Executed jobs (if configured) `

Access Control

User Access Management

#### Allow Specific Users Create /etc/at.allow with usernames (one per line): ` root admin developer `

#### Deny Specific Users Create /etc/at.deny with usernames to block: ` guest temporary restricted_user `

Access Control Logic

| Condition | Result | |-----------|--------| | at.allow exists | Only listed users can use at | | at.allow doesn't exist, at.deny exists | All users except those in at.deny can use at | | Neither file exists | Only root can use at | | Both files exist | at.allow takes precedence |

Security Considerations

#### File Permissions `bash

Secure configuration files

sudo chmod 640 /etc/at.allow /etc/at.deny sudo chown root:root /etc/at.allow /etc/at.deny

Secure spool directory

sudo chmod 1770 /var/spool/at `

#### Environment Security Jobs run with the user's environment at the time of scheduling: `bash

View environment that will be used

at -c job_id | head -20 `

Advanced Usage

Working with Different Queues

#### Queue Priority System Queues are processed in alphabetical order: - Queue 'a' has highest priority - Queue 'z' has lowest priority - Uppercase letters have lower priority than lowercase

#### Queue Management Examples `bash

Critical system task

echo "critical_backup.sh" | at -q a now + 1 hour

Regular maintenance

echo "log_rotation.sh" | at -q m midnight

Low priority cleanup

echo "temp_cleanup.sh" | at -q z now + 6 hours `

Batch Processing

#### Using batch Command The batch command is equivalent to at -q b now: `bash batch << EOF find /tmp -type f -mtime +7 -delete optimize_database.sh EOF `

#### Load Average Control `bash

Configure load average limit

echo 'OPTIONS="-l 2.0"' | sudo tee /etc/default/atd sudo systemctl restart atd `

Integration with Scripts

#### Script-Based Job Creation `bash #!/bin/bash

schedule_maintenance.sh

MAINTENANCE_TIME="02:00 tomorrow" SCRIPT_PATH="/opt/maintenance/daily_tasks.sh"

echo "$SCRIPT_PATH" | at "$MAINTENANCE_TIME" echo "Maintenance scheduled for $MAINTENANCE_TIME" `

#### Dynamic Job Scheduling `bash #!/bin/bash

dynamic_scheduler.sh

for server in web1 web2 db1; do echo "ssh $server 'system_check.sh'" | at now + $((RANDOM % 60)) minutes done `

Error Handling and Logging

#### Comprehensive Error Handling `bash at now + 5 minutes << 'EOF' #!/bin/bash LOG_FILE="/var/log/at_job_$(date +%Y%m%d_%H%M%S).log" exec > "$LOG_FILE" 2>&1

echo "Job started at $(date)"

Your actual commands here

if command1; then echo "Command1 succeeded" else echo "Command1 failed with exit code $?" fi

echo "Job completed at $(date)" EOF `

#### Mail Configuration `bash

Ensure mail delivery

echo "task_with_output.sh 2>&1 | mail -s 'Job Results' user@example.com" | at now + 1 hour `

Troubleshooting

Common Issues and Solutions

#### atd Service Not Running `bash

Check service status

systemctl status atd

Start if stopped

sudo systemctl start atd sudo systemctl enable atd `

#### Jobs Not Executing `bash

Check system time

date

Verify job scheduling

atq

Check logs

sudo journalctl -u atd -n 50 `

#### Permission Denied Errors `bash

Check access control files

ls -la /etc/at.allow /etc/at.deny

Verify user permissions

groups $USER `

Debugging Job Execution

#### Job Content Verification `bash

Display job contents

at -c job_id

Check environment variables

at -c job_id | grep -E '^[A-Z_]+=|^export' `

#### Log Analysis `bash

System logs

sudo grep -i "atd\|at\[" /var/log/syslog

Mail logs for job output

sudo grep -i "at.*job" /var/log/mail.log `

Performance Issues

#### High Load Average `bash

Monitor system load

uptime

Adjust atd load limit

echo 'OPTIONS="-l 1.0"' | sudo tee -a /etc/default/atd sudo systemctl restart atd `

#### Queue Management `bash

Check queue lengths

atq | wc -l

Monitor job execution

watch -n 5 'atq | wc -l' `

Comparison with Other Scheduling Tools

at vs cron vs systemd timers

| Feature | at | cron | systemd timers | |---------|----|----- |----------------| | Purpose | One-time jobs | Recurring jobs | Both one-time and recurring | | Time specification | Flexible natural language | Cron syntax | Calendar and monotonic | | User interface | Command line | Crontab file | systemctl commands | | Dependency handling | None | Limited | Advanced | | Logging | Mail/syslog | Syslog | journald | | Resource control | Load average | None | Comprehensive |

When to Use Each Tool

#### Use at when: - Scheduling one-time tasks - Need flexible time specification - Quick ad-hoc job scheduling - Simple task execution

#### Use cron when: - Recurring scheduled tasks - System maintenance jobs - Regular backup operations - Established scheduling patterns

#### Use systemd timers when: - Complex dependency requirements - Resource control needed - Integration with systemd services - Advanced logging requirements

Best Practices

Security Best Practices

#### Environment Management `bash

Set secure PATH in jobs

at now + 1 minute << 'EOF' export PATH="/usr/local/bin:/usr/bin:/bin"

Your commands here

EOF `

#### File Permissions `bash

Create scripts with appropriate permissions

chmod 750 /path/to/script.sh chown user:group /path/to/script.sh `

Operational Best Practices

#### Job Documentation `bash

Include descriptive comments in jobs

at midnight << 'EOF' #!/bin/bash

Daily log rotation job

Scheduled by: admin

Purpose: Rotate and compress application logs

/usr/sbin/logrotate /etc/logrotate.conf EOF `

#### Error Handling `bash

Always include error handling

at now + 5 minutes << 'EOF' #!/bin/bash set -e # Exit on error set -u # Exit on undefined variable

trap 'echo "Job failed at line $LINENO"' ERR

Your commands here

EOF `

#### Resource Management `bash

Monitor resource usage

at -q z now + 1 hour << 'EOF' #!/bin/bash

Use nice to lower priority

nice -n 19 resource_intensive_task.sh EOF `

Maintenance Best Practices

#### Regular Cleanup `bash

Clean up old job files (if applicable)

find /var/spool/at -name "a*" -mtime +30 -type f -delete `

#### Monitoring `bash

Create monitoring script

#!/bin/bash

at_monitor.sh

QUEUE_COUNT=$(atq | wc -l) if [ "$QUEUE_COUNT" -gt 100 ]; then echo "Warning: $QUEUE_COUNT jobs in at queue" | mail -s "High at Queue" admin@example.com fi `

#### Backup Considerations `bash

Backup scheduled jobs list

atq > /backup/scheduled_jobs_$(date +%Y%m%d).txt `

This comprehensive guide covers all aspects of the at command, from basic usage to advanced configuration and troubleshooting. The at command remains an essential tool for system administrators and users who need to schedule one-time tasks efficiently and reliably.

Tags

  • Automation
  • Command Line
  • Linux
  • system-administration
  • task-scheduling

Related Articles

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

Complete Guide to Linux at Command: Schedule One-Time Jobs