Home Linux Commands How To Schedule Tasks Using Linux at Command

How To Schedule Tasks Using Linux at Command

Linux at Command Demystified: Schedule Tasks with Ease.

By sk
1.7K views

In Linux, when we want to make our computer perform tasks automatically, we use something called scheduling. It's like telling the computer, "Do this thing at this time." This makes our work easier because we don't have to remember to do those tasks ourselves. One way to do this is by using the Linux at command. The at command can serve as an alternative to the cron command when you have tasks that need to run only once at a specific time in the future.x

The "at" command lets us schedule tasks to happen at specific times. So, if we want the computer to do something like creating a backup or sending an email, we can use the "at" command to tell it when to do it. It's like setting an alarm for your computer to do things for you.

In this guide, we'll dive into the Linux at command and see how it helps us schedule tasks effortlessly. We'll explore 11 at command examples for scheduling tasks in Linux. Whether you're new to Linux or already familiar, learning about the "at" command can make your life simpler by automating tasks on your computer.

What is Linux at Command?

The at command in Linux is used to schedule a one-time task to be executed at a specific time in the future. It allows you to specify a particular time when the command or script should run.

The at command can be useful for automating one-time tasks, such as backing up files, running scripts, or sending emails.

cron Vs at

When you're in the process of scheduling tasks, you might encounter the terms "cron" and "at" and find yourself questioning the distinctions between the cron and at commands in the Linux environment.

The at command and the cron command are both used for scheduling tasks in Linux, but they have distinct differences in terms of how they work and when they are best suited to use.

The cron utility enables you to schedule recurring tasks at specific intervals, while the at command enables you to specify one-time actions to be performed at a desired time. For instance, you could utilize crontab to schedule a daily backup at 2 a.m., ensuring repetitive execution. Conversely, you could use the at command to create a reminder for a later appointment within the day, focusing on a single occurrence.

In essence, we usually use the at command for one-time tasks scheduled at specific moments, and use the cron command for automated, recurring tasks that need to be executed on a regular basis.

The choice between them depends on the nature of your tasks and how often you want them to run.

Install at Command in Linux

The at command is usually pre-installed on many Linux distributions. However, if it's not available on your system, you can install it using package managers specific to your distribution. Here are the installation steps for some common Linux distributions:

Alpine Linux:

To install at command in Alpine Linux, run:

$ sudo apk add at

Arch Linux / Endeavour OS / Manjaro Linux:

Open a terminal and run the following command:

$ sudo pacman -S at

Debian / Ubuntu / Linux Mint / Pop!_OS:

Run the following commands to install 'at' in Debian-based systems:

$ sudo apt update
$ sudo apt install at

RHEL / CentOS Stream / Fedora / AlmaLinux / Rocky Linux:

Open a terminal and run the following command:

$ sudo dnf install at

In older RHEL systems, use yum instead of dnf.

$ sudo yum install at

After the installation is complete, you can start using the at command to schedule tasks at specific times.

Start 'at' Service

The atd service should start automatically after installation. If it's not running, you can start and enable it with the following commands:

$ sudo systemctl start atd
$ sudo systemctl enable atd

Linux at Command Examples

The Linux at command is easy to use. You simply specify the time you want the task to run, and the command you want to run. The at command will then create a job file and store it in the /var/spool/cron/atjobs/ directory. When the specified time arrives, the at command will execute the job file.

Here are some examples of using the at command to schedule one-time tasks in Linux.

1. Scheduling Jobs Interactively using 'at' Command

The at command enables you to schedule jobs interactively by using the following syntax:

at [runtime]

When you run this command, it opens an interactive prompt where you can input the commands that you want to execute at the specified time. Additionally, the command displays a warning indicating the shell (E.g. /bin/sh) that will be used for the scheduled job.

To save the scheduled job and exit the interactive prompt, press Ctrl + D. If you wish to cancel the job before saving it, you can use Ctrl + C.

Take a look at the following example.

$ at 2:37 PM
echo "Hello, Welcome to OSTechNix!" > /tmp/greeting.txt
<Ctrl+D>
Scheduling Jobs Interactively
Scheduling Jobs Interactively

This example will schedule the echo command to run at 2:37 PM. The output "Hello, Welcome to OSTechNix!" will be written to the file /tmp/greeting.txt at the specified time.

After scheduling the job, wait for the specified time to elapse. Once the scheduled time is reached, you can verify whether the message has been saved in the greeting.txt file located in the /tmp directory.

$ sudo cat /tmp/greeting.txt
[sudo] password for ostechnix:
Hello, Welcome to OSTechNix!
Display File Content with cat Command
Display File Content with cat Command

Yes, the Job is successfully executed at the specified time.

In this example, we scheduled the echo "Hello, Welcome to OSTechNix!" > /tmp/greeting.txt command to run at a specific time using the at command. After the scheduled time has passed, we checked the content of the greeting.txt file to verify that the script executed successfully and saved the message as expected.

2. List Scheduled Jobs

You can list all the scheduled jobs in the 'at' queue using command:

$ atq

Sample Output:

4 Wed Aug 8 14:37:00 2023 a ostechnix

The atq command lists the scheduled jobs in the 'at' queue. The displayed information includes the job number, date, time, year, and queue status for the current user's pending tasks. In this case, job number 4 is scheduled to run at 14:37 PM on August 8, 2023 for the user ostechnix.

To view the pending jobs for all users, execute the command with administrative privileges:

$ sudo atq

The above command retrieves the list of pending at jobs, and when executed with sudo, it provides an overview of pending jobs for all users on the system.

You can also use -l flag with 'at' command to view the scheduled jobs.

$ at -l

The at -l is just an alias to atq command.

3. Previewing Scheduled Jobs

Using the -c option, you can preview the contents of a job that was previously scheduled using the at command. This option comes handy when you need to know about the job's details or if you want to check its scheduled time.

To view the contents of a scheduled at job, run the following command

$ at -c [job_number]

Example:

$ at -c 7

Sample Output:

#!/bin/sh
# atrun uid=1000 gid=1000
# mail ostechnix 0
umask 22
LANGUAGE=en_IN:en; export LANGUAGE
PWD=/home/ostechnix; export PWD
LOGNAME=ostechnix; export LOGNAME
XDG_SESSION_TYPE=tty; export XDG_SESSION_TYPE
[...]

To identify the specific job number, you should run the atq command initially. This will provide a list of all pending jobs along with their associated job numbers.

4. Pipe a Job to 'at' Command

You can schedule a job without using the interactive at prompt by sending the commands to at through a UNIX pipe. This involves using commands like echo or printf to pass instructions to the at command while also specifying the desired runtime.

For instance, to schedule an at job that takes the output of the echo command and writes it to a file, you can use:

$ echo "Welcome to the tutorial on Linux 'at' Command" >> Linux_at_command.txt | at now

This job will immediately run.

Sample Output:

warning: commands will be executed using /bin/sh
job 6 at Wed Aug 9 12:50:00 2023

After scheduling the job, you can verify its execution by checking the existence of the file using the cat command:

$ cat Linux_at_command.txt 
Welcome to the tutorial on Linux 'at' Command

In this manner, you can efficiently schedule tasks using the at command without needing to interactively input each command separately.

5. Scheduling Scripts

Not just commands, we can also schedule a script to run at a specific time using the at command like below.

at 2:00 AM tomorrow
/path/to/my_script.sh
<Ctrl+D>

This example will schedule the execution of my_script.sh at 2:00 AM on the next day. Please replace the path of the script with your own.

Let us see a practical example, so you can understand it clearly.

1. Create a script called testscript.sh:

$ cat << EOF > testscript.sh
> echo "Hello, Welcome to OSTechNix!" > /tmp/greeting.txt
> EOF

This command uses a heredoc (<<) to create a script called testscript.sh with the content that follows until EOF. The script simply echoes the text "Hello, Welcome to OSTechNix!" into a file named /tmp/greeting.txt.

2. Make the script executable:

$ sudo chmod +x testscript.sh

This command gives the script testscript.sh the execute permission using chmod. Now the script can be executed as a standalone program.

3. Check the current date and time:

$ date

Sample Output:

Wednesday 09 August 2023 12:16:04 PM IST

As you can see, the exact time at the time of running this command is 12:16:04 PM.

4. Let us now schedule the script testscript.sh to run at a later time (E.g. 12:18 PM) using the at command:

$ at 12:18 PM -f ./testscript.sh

Sample Output:

warning: commands will be executed using /bin/sh
job 5 at Wed Aug  9 12:18:00 2023

This command schedules the execution of the testscript.sh script at 12:18 PM on August 11, 2023. The warning message indicates that the commands will be executed using the /bin/sh shell.

5. Check the scheduled jobs in the at queue:

$ atq

Sample Output:

5 Wed Aug 9 12:18:00 2023 a ostechnix

The atq command lists the scheduled jobs in the at queue. In this case, job number 5 is scheduled to run at 12:18 PM on August 9, 2023.

6. Now wait for the specified time to elapse. Once the scheduled time is reached, check again the 'at' queue:

$ atq

The atq command output should now be empty because the scheduled job has already been executed.

7. Check the contents of /tmp/greeting.txt after the script has run:

$ cat /tmp/greeting.txt

Sample Output:

Hello, Welcome to OSTechNix!
Scheduling Scripts using Linux 'at' Command
Scheduling Scripts using Linux 'at' Command

As you see in the above output, the cat command displays the contents of the file /tmp/greeting.txt, which was created by the script testscript.sh.

6. Scheduling Jobs using a Specific Date and Time Format

If you want to schedule a command using a specific date and time format, do:

$ at 01:47PM 2023-08-09
warning: commands will be executed using /bin/sh
at Wed Aug  9 13:47:00 2023
at> echo "This is a scheduled task using a specific date and time format." > /tmp/date.txt
at> <EOT>
job 11 at Wed Aug  9 13:47:00 2023

In this case, the at command is telling the system to schedule a job to run at 01:47 PM on August 9th, 2023.

You can read more about 'Time Expressions' later in this guide.

7. Send Email Notification on Job Completion

To send email notifications upon job completion using the at command, you can follow these steps:

1. Ensure that your system has a working email configuration, and your user account is associated with a valid email address.

2. To instruct at to send email notifications upon job completion, even if there is no output, you need to specify the -m option when scheduling the job.

For example, to run a script named testscript.sh and receive an email notification upon completion:

$ cat testscript.sh | at -m now + 1 hour

In this case, testscript.sh is piped to the at command, and the -m option is used to ensure an email notification is sent when the job completes.

3. Once the job completes, you should receive an email notification at the configured email address associated with your user account. The email will contain information about the job execution.

Keep in mind that the effectiveness of this approach depends on your system's email configuration. If you encounter issues, ensure that your system is set up to send emails and that your user's email address is correctly configured.

8. Schedule Jobs without Email Notification

To prevent receiving email notifications upon job completion, you can utilize the -M option while scheduling an at job.

For instance:

$ echo "testscript.sh" | at -M 02:00

By including the -M option in the at command, you ensure that job execution occurs without generating email notifications upon completion.

This is particularly useful when you want to execute tasks silently without being alerted by email notifications.

9. Remove Scheduled Jobs

To remove a scheduled job using the at command, you can use either the atrm command or use -r option with at command followed by the job ID. Here are the steps for both methods:

9.1. Using atrm command

Identify the job ID of the scheduled job by running the atq command or using the -l option with the at command.

Run the following command to remove the job with the specified job ID:

$ atrm [job_id]

Replace [job_id] with the actual job ID you want to remove.

Example:

1. First, list all scheduled jobs using atq command:

$ atq

Sample Output:

7	Sun Mar 14 13:31:00 2230 a ostechnix
9	Fri Aug  9 13:40:00 3241 a ostechnix
8	Sun Mar 14 13:33:00 2230 a ostechnix
10	Wed Aug  9 13:42:00 3245 a ostechnix

As you can see, there are 4 pending jobs exists.

2. To delete a job, for example the job with the ID 7, run:

$ atrm 7

3. verify if the job is deleted by listing the scheduled jobs :

$ atq
9	Fri Aug  9 13:40:00 3241 a ostechnix
8	Sun Mar 14 13:33:00 2230 a ostechnix
10	Wed Aug  9 13:42:00 3245 a ostechnix
Remove Scheduled Jobs
Remove Scheduled Jobs

See? The the 7th job is gone.

9.2 Using at -r Option

Identify the job ID of the scheduled job by running the atq command or using the -l option with the at command.

Run the following command to remove the job with the specified job ID:

$ at -r [job_id]

Replace [job_id] with the actual job ID you want to remove.

Remember that you need appropriate privileges (usually root or sudo access) to remove jobs scheduled by other users. If you're the owner of the job, you can typically remove it without additional permissions.

10. Allow or Deny Users

The /etc/at.allow and /etc/at.deny files are used to control user access to the at and batch commands, which allow users to schedule tasks for later execution. These files determine which users are allowed to submit commands for later execution using the at and batch commands.

Both files have a list of usernames, with each username listed on a separate line. Whitespace is not allowed.

If /etc/at.allow exists, only usernames mentioned in this file are granted permission to use the at command. If /etc/at.allow is empty or doesn't exist, access control is determined by the /etc/at.deny file.

If /etc/at.allow doesn't exist or doesn't grant access to a specific user, the /etc/at.deny file is checked.
Users not listed in /etc/at.deny are allowed to use the at and batch commands.

If /etc/at.deny is empty, all users have the privilege to use the at command.

If neither /etc/at.allow nor /etc/at.deny exists, only the superuser (root) is allowed to use the at and batch commands.

The /etc/at.allow file takes precedence over /etc/at.deny file. If a user is listed in both files, access is granted based on /etc/at.allow.

These files provide a simple yet effective means of controlling which users can utilize the at and batch commands to schedule tasks for later execution on the system.

Let us see how to restrict users from using at command with an example.

To restrict users from using the at command, you can utilize the /etc/at.allow and /etc/at.deny files. Here's how you can do it:

10.1. Using /etc/at.deny

Open the /etc/at.deny file with a text editor and add the usernames of the users you want to restrict, each on a separate line. Save and exit the file.

For example, to restrict users "user1" and "user2," you can run:

$ echo "user1" | sudo tee -a /etc/at.deny
$ echo "user2" | sudo tee -a /etc/at.deny

Now switch to any restricted user and try to run any 'at' command:

$ su - user1
$ atq
You do not have permission to use atq.
Restrict Users from Running 'at' Command
Restrict Users from Running 'at' Command

10.2. Using /etc/at.allow

If you prefer allowing only specific users to use the at command, you can create the /etc/at.allow file and add the usernames of the users who are allowed to use the command, each on a separate line.
Save and exit the file.

For example, to allow only "ostechnix" to use the at command, you can run:

$ echo "ostechnix" | sudo tee -a /etc/at.allow

Remember that the /etc/at.allow file takes precedence over the /etc/at.deny file. If a username is listed in both files, the user will be allowed to use the at command.

After making these changes, the users you have restricted will no longer be able to use the at command.

11. Execute Jobs When System Load Permits

The "batch" command carries out tasks when the system's load conditions are favorable. Specifically, it triggers execution when the load average falls below 1.5 or the specified value set during the invocation of the "atd" daemon. This approach helps ensure that the jobs run during periods of lower system activity.

Here's how you can use the batch command to execute jobs when the system load permits:

1. Open a terminal.

2. Type batch and press Enter. This will initiate the batch command and provide you with a prompt where you can enter the commands you want to execute.

3. Enter the commands you want to execute once the system load drops below the threshold. For example:

echo "Job started at $(date)" >> job_log.txt
sleep 5
echo "Job finished at $(date)" >> job_log.txt

In this example, the job logs the start time, waits for 5 seconds using the sleep command, and then logs the finish time.

4. Press Ctrl + D to indicate that you're done entering commands. The commands you entered will be queued for execution when the system's load average is below the threshold.

Execute Jobs When System Load Permits
Execute Jobs When System Load Permits

5. The system will execute the queued commands when the load average drops below the specified threshold, which is usually around 1.5.

6. Verify if the batch job is completed by viewing the contents of job_log txt file.

$ cat job_log.txt 
Job started at Wednesday 09 August 2023 03:48:06 PM IST
Job finished at Wednesday 09 August 2023 03:48:11 PM IST

Keep in mind that the batch command relies on the system's load conditions, so there might be a delay before your jobs actually run, depending on the load on the system at the moment.

It's worth noting that the actual behavior of the batch command may vary slightly depending on the specific implementation on your system.

Time Expressions

The at command accepts various time formats for scheduling jobs. For instance, you can use HH:MM to schedule a job at a particular time of the day. If that time has already passed, the job is assumed to run on the next day.

Notably, you have the option to specify specific times like midnight, noon, or teatime (4pm). Additionally, you can suffix a time with AM or PM to indicate morning or evening.

You can also indicate the day the job should be executed. This can be done by providing a date in formats such as month-name day (with an optional year), MMDD[CC]YY, MM/DD/[CC]YY, DD.MM.[CC]YY, or [CC]YY-MM-DD. The date specification must follow the time of day specification.

Moreover, you have the flexibility to define relative times, such as now + count time-units. The time-units can be minutes, hours, days, or weeks.

To specify running a job today, you can simply suffix the time with "today." Similarly, suffixing the time with "tomorrow" will schedule the job for the following day.

Examples:

For instance, if you wish to run a job at 2pm 5 days from now, you can use the syntax:

at 2pm + 5 days 

To schedule a job for 11:00am on August 31, you can use:

at 11am Aug 31

For a job at 3am tomorrow, the command would be:

at 3am tomorrow

In cases where you specify a job to run at a time and date in the past, the job will execute as soon as possible. For example, if it's currently 11pm and you schedule a job for 9pm on the same day using at 9pm today, the job is likely to run around 11:05pm.

The following table provides a clear breakdown of the different time expressions and how they can be used to schedule jobs using the at command.

Time ExpressionDescriptionExample
HH:MMSchedule a job at a specific time of day.at 4pm
midnight, noon, teatimeSpecial times of the day.at midnight
AM or PMMorning or evening time specification.at 8:30AM
month-name daySpecify a job's day with an optional year.at 10am Jul 31
MMDD[CC]YY, MM/DD/[CC]YY, DD.MM.[CC]YY, [CC]YY-MM-DDVarious date formats.at 03142230 (for March 14, 2023, 10:30 PM)
now + count time-unitsRelative time specification.at now + 2 hours
today, tomorrowSchedule a job for today or tomorrow.at 1am tomorrow
Linux 'at' Command Time Expression

You can find further details about the time specification format in the file /usr/share/doc/at/timespec.

Linux at Command Cheat Sheet

Here's the Linux at command cheat sheet in a tabular column format. Please print it and keep it nearby for quick reference.

TaskCommandExample
Schedule at a specific timeat <time>at 3:30 PM
Schedule after a delayat now + <time>at now + 2 hours
Schedule using a script fileat <time> -f <script_file>at 9:00 AM tomorrow -f script.sh
Interactive promptat
Execute commandsat <time> <<< "command"at 5:00 PM <<< "backup.sh"
View pending jobsatq or at -l
Remove a jobatrm <job_id> or at -r <job_id>atrm 3 or at -r 3
View job contentsat -c <job_id>at -c 5
Send email notificationsecho "command" | at -m <time>echo "backup.sh" | at -m 11:00 PM
Suppress email notificationsecho "command" | at -M <time>echo "command" | at -M 8:00 AM
Access helpat -h or man at
Linux at Command Cheat Cheat

Remember that the at command's behavior may vary slightly between different Linux distributions. Use this cheat sheet as a quick reference guide for using the at command effectively.

Frequently Asked Questions

Here's a list of FAQs for Linux at and batch commands.

Q: What is the at command in Linux?

A: The at command is a utility in Linux that allows you to schedule one-time tasks or commands to run at a specific time in the future. It's particularly useful for automating tasks without requiring user intervention.

Q: How do I use the at command to schedule jobs?

A: To schedule tasks using Linux at command, follow the steps below:
1. Open a terminal.
2. Use the following syntax to schedule a job:
at [time] [date]
For example:
at 10:30AM tomorrow
3. Press Enter and you'll enter an interactive prompt where you can enter the commands you want to execute.
4. Press Ctrl + D when you're done entering commands to schedule the job.

Q: Can I specify a command file instead of typing commands interactively?

A: Yes, you can use the -f option to specify a file containing the commands you want to execute. For example:
at 2:00PM -f script.sh

Q: How can I see the list of scheduled jobs?

A: Use the atq command to list the pending jobs along with their job IDs and scheduled times.

Q: Can I view the contents of a scheduled job?

A: Yes, you can use the -c option followed by the job ID to display the contents of a previously scheduled job. For example:
at -c 123

Q: How do I remove a scheduled job?

A: You can use the atrm command followed by the job ID to remove a scheduled job. For example:
atrm 123

Q: Can I receive email notifications for job completion?

A: By default, the at command sends email notifications about completed jobs. You can enable it even for jobs with no output using the -m option.

Q: Can I disable Email notifications?

A: Yes, you can disable this behavior using the -M option.

Q: What formats can I use for specifying time and date?

A: You can use formats like HH:MM, midnight, noon, teatime, specific dates (e.g., Jul 31, 2023), relative times (e.g., now + 2 hours), today, and tomorrow.

Q: Can I use the at command for recurring tasks?

A: No, the at command is designed for one-time scheduling. For recurring tasks, consider using the cron command.

Q: What is the batch command?

A: The batch command is a utility that allows you to schedule jobs to run when the system's load average drops below a certain threshold, typically around 1.5. It helps ensure that jobs are executed during periods of lower system activity.

Q: How does the batch command work?

A: The batch command schedules jobs to run in a queue when the system's load conditions permit. It monitors the load average and initiates job execution when the load drops below the specified threshold.

Q: How do I use the batch command?

A: The batch command usage is same as at command's.
1. Open a terminal.
2. Type batch and press Enter to start the batch command.
3. Enter the commands you want to execute when the load drops below the threshold.
4. Press Ctrl + D to indicate the end of command input.

Q: What kind of jobs are suitable for the batch command?

A: The batch command is ideal for non-urgent tasks that can be executed when the system is less busy. Examples include data backups, log analysis, or resource-intensive tasks that can be postponed until the system load decreases.

Q: How can I check the status of jobs scheduled with batch?

A: You can use the atq command to check the status of pending jobs scheduled with batch. It will display the list of jobs in the queue along with their job IDs.

Q: Can I cancel or remove jobs scheduled with the batch command?

A: Yes, you can cancel scheduled jobs using the atrm command followed by the job ID. For example, atrm 123 will remove job number 123 from the queue.

Q: How can I get help with using the at and batch commands?

A: To access help for the at command, simply type at -h or man at in the terminal. You can also locate the help section for the batch command within the manual page of the at command.

Conclusion

In conclusion, the Linux at command is a handy tool that lets you schedule tasks to happen at specific times in the future. It's like setting an alarm for your computer to do things for you automatically.

So, whether you're new to Linux or an experienced user, the Linux at command can make your life easier by taking care of tasks at the right time.

You May Also Like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. By using this site, we will assume that you're OK with it. Accept Read More