Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Hard

Linux Crontab and At

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Linux is an open-source kernel for operating systems. It is widely used in operating systems such as Ubuntu, Debian, etc. One of the unique features of Linux is that it allows the user to have a higher degree of control over the machine. We can execute and program a vast number of things into our computer using simple commands.

Linux Crontab and At

Scheduling processes and commands is one of these things. If we wish to schedule a particular script to run next Monday, how would we do so? This is what we will look at in our article. There are 2 basic commands that we can use for this - at and crontab. Let's look at them both!

At Command

The at command can be used to schedule a job to run at a specific time. We can send reminders, execute system updates, and take backups at our desired time. We can specify a specific time and date (such as 12th October at 12 AM) or an interval (such as after 3 hours). 

Let's look at it in detail, as well as the commands related to it. 

Installing

at needs to be installed first. We can use apt-get to install it. Run the command:

sudo apt-get install at
Installing at
At has been installed

Once it is installed, we must start it and enable it. We can do so by running the commands:

sudo systemctl start atd
sudo systemctl enable atd 


(sudo might not be required, depending on the user's privileges).

Start and Enable At service

Now, we can begin using the at command.

Basic Example

Let's schedule a basic task using at. We will simply output something to the terminal at the specified time. 

Perform the command as given in the image. You may change the time according to your convenience. The system time when this command was written was 1:25 PM. 

Writing a demo at script

We can exit the input by pressing Ctrl+D.

No file exists

We can see no file exists at the moment, after the command is executed- a file demo.txt will be created.

File is created after at command executes

As we can see, after the time set passed, our command was executed, and our file was created. 

Time Specification Format

We can specify the time in many ways and add fields such as days and months. 

The rules to be followed are

  1. Time should be specified as HH: MM. If it is not in 24 hour format, we should specify AM or PM after it. We can also write midnight (12 AM), noon (12 PM), or teatime (4 PM).
     
  2. Dates can be specified as MMDDYYMM/DD/YY, or DD.MM.YY, or YYYY-MM-DD. We can also write it as month-name day year, where year is optional. Time must always be specified after the date.
     
  3. We can also give times as now + count of time_units. The time units can be minutes, hours, days, or weeks. So we can write something like - now + 5 hours, meaning 5 hours from now.
     
  4. We can tell at to run the job today by adding today at the end of the command, and we can do the same for tomorrow
     

Let's see a few examples.

1.  To schedule a task at 10 PM next Monday:

at 10:00 PM Tuesday


2. To schedule a task at 10 PM on Dec 22nd:

at 10:00 AM december 22


(If December 22 has passed, the next year's December 22 will be considered)
 

3. To schedule a task at 10 PM tomorrow:

at 10:00 AM tomorrow


4. To schedule a task at 2 hours from now:

at now +2 hours


5. To schedule a task for next Tuesday, 3 hours from the current time.

at Tuesday + 3 hours


6. To schedule a task on 12 November 2022 at 12:45 PM

at 121122 12:45 PM


You can find the exact specification of the time formats in the folder located at /usr/share/doc/at-3.1.10/timespec (version may vary). Different versions may have slight formats changes, so checking this file is recommended.

Options

The various options available for the at command are as follows.

  • -V 

    Prints the version number of at.
     
  • -q 

    At allows us to structure different jobs into different queues. This option lets us specify which queue we want to put our job in. Queues are specified by single letters from a to z and A to Z. Queues with higher letters have lesser priorities. The special queue "=" shows jobs currently running. 
     
  • -m 

    This option sends a mail to the user when the job completes, even if there is no output.
     
  • -f 

    This reads the job from a file instead of standard input.
     
  • -l 

    This runs the atq command.
     
  • -d 

    This runs the atrm command.
     
  • -v 

    Shows the execution time of the job before reading the commands to perform.
     
  • -c 

    Outputs the listed jobs to standard output.
     
  • -t 

    Lets us specify the time in the format ([[CC]YY]MMDDhhmm)

atq

To list all the jobs currently pending, type the command

at
atq command output

The numbers on the left represent the jobid. It starts from 1 and is increased whenever a new job is added. We see it here starting from 5 because 4 jobs were earlier added that were completed. 

The jobs are listed in execution order, not addition order.

atrm

atrm is used to delete a pending job. For e.g., if we want to delete the job with jobid 5, we can type

atrm 5
Deleting an at job using atrm

No output means the job has successfully been deleted.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Crontab

One limitation of the at command is that we can't use it to run recurring tasks. For example, if I want to run a task every Monday, we can't use at to accomplish this. For this, we use crontab. Before we see what crontab is, let us look at the cron daemon first.

Cron Daemon

The cron daemon is a background process that is always running on a Linux machine. It is used to schedule jobs at regular time intervals, at specific recurring intervals, or on a particular date and time.

Cron Tables - known as crontab for short, are where the commands to be run, and the times to run them are stored. 

Crontab

A crontab file is a simple plain text file in which each line represents a job. They are usually in the /etc folder (or its subdirectories), and each user has their own crontab file. Crontab files contain all of the scheduled jobs of a particular user. It is a text file that each user can edit and add their tasks to. The tasks can be scheduled to run once, or they can also be recurring (eg - running every week on Monday at 8 PM, yearly on January 1 at 12 AM, etc.)

In many cases, a systemwide crontab file also exists - that only the system administrator is allowed to edit. Each line in a crontab file represents a job that should be run on a particular schedule. There is a specific format in which we must define each job. 

Format for Crontab

Each line must have five fields, separated by a space - followed by the command or the script to execute. It looks like this:

Format for Crontab

Each * must be replaced by the value for the corresponding field. For example, if we want to execute our command on a Monday, we will replace the Day of Week field with 1. 

* values can be left when we want our command to occur for all values of that field. For e.g., if we want to execute our command every Monday, no matter what the Month is, then we can leave * in the month field. 

We can also specify values using commas, dashes, and / sign 
Commas - When commas are used, all comma-separated values are accepted. For e.g., to run a command on the 5th and 8th of a month, we can set the Day of Month as 

5,8 

Dashes - If we set a value as x-y, all values between x and y are accepted. For example, to execute a command in the first 15 days, we can write Day of Month as 

1-15

/ Symbol - This is used to specify intervals. If we want a job to be done every 10 minutes, we can set the minute field as 

*/10

Special keywords also exist that we can use instead of specifying all 5 values:

  • @yearly - equivalent to 0 0 1 1 *
  • @daily  - equivalent to 0 0 * * *
  • @hourly - equivalent to 0 * * * * 
  • @reboot - Runs the command whenever the system reboots. 
     

NOTE - If the day of the week and the date of the month both are specified, the command will run when the current time satisfies either one or both of those values. For e.g., if the date was set as the 5th and the Day was set as 1 (Monday), then the command will run on all 5ths (even if they are not Mondays) and all Mondays (even if the date is not 5th), and also on 5ths that are Mondays.

Example crontab formats

1. Every Monday at 12 AM.

0 0 * * 1


2. The 5th of every month at 5 PM.

0 17 5 * *


3. Hourly on every Monday.

0 * * * 1


4. Every hour during working hours, on weekdays.

0 9-17 * * 1-5


5. Every 10 minutes on Mondays and Wednesdays

*/10 * * * 1,3

Usage

Cron is installed by default, so we do not have to install it. However, we may have to create a crontab file for the current user. If it has not been created yet, there will be no crontab file by default. 

We can check this by running:

crontab -l 
Check if crontab exists

This means there is no crontab file for the user named admin.

We will create one by typing the command:

crontab -e
Create crontab

You can choose any editor you like. We are choosing nano. You should see this screen.

Crontab opens in text editor

At the end, write a sample cron command such as

*/1 * * * * echo "Hi Ninja";date; >> ~/crontest.txt
Sample cron command

This will create a file called crontest.txt in our home directory, and add a line "Hi Ninja" to it every minute. The current date of the system will also be added to the file whenever the command runs. Exit the editor (Ctrl +X in nano, :wq in Vim). If prompted to save the file, choose Yes.

Crontab created

You should see this output. Verify it by running crontab -l again.

Verify by running crontab -l

The file you just created should be visible.

In your home directory, check if the file has been created.

File has been created

Let's see it and check.

File contains correct output, with date

We can see we have one entry, corresponding to 19:52 UTC. We will wait another minute and see it once more.

File has been written to again after 1 minute

We can see exactly another minute later, another entry has been created. Thus, we can verify that our crontab works!

Frequently Asked Questions

What are the major differences between using at and using crontab?

The biggest difference is in functionality, which is because at cannot be used to do recurring tasks. At will only perform a task exactly once. If we wish to perform it again, we need to write another at command for it. Crontab can handle recurring tasks easily. Another difference is that crontab uses a file to store its commands, with at we use the command line and use it as a command.

How are different time zones handled?

Generally, the cron daemon simply uses the time zone of the local machine. However, if it is a large machine and people around the world are using it, it must cater to different time zones. For this, special implementations of cron exist that allow each user to set their own time zone by specifying a CRON_TZ value in the crontab.

Can one user edit another user's crontab?

No, this is not possible. Each user can only edit its own crontab. However, the root user is allowed to edit all crontab files. 

Conclusion

This blog has explored what crontab and at commands are in Linux. We have seen examples of both, and the different use cases of both of them. 

We hope you leave this article with a broader knowledge of Linux, processes, cron, and running commands over CLI. We recommend that you explore our different articles on these topics as well, such as:

Introduction to Linux

Linux Kernel

Linux Directories

 

You can practice questions on various problems on Coding Ninjas Studio, attempt mock tests. You can also go through interview experiences, interview bundle, go along guided paths for preparations, and a lot more!

Keep coding, keep reading Ninjas. 

Topics covered
1.
Introduction
2.
At Command
2.1.
Installing
2.2.
Basic Example
2.3.
Time Specification Format
2.4.
Options
2.5.
atq
2.6.
atrm
3.
Crontab
3.1.
Cron Daemon
3.2.
Crontab
3.3.
Format for Crontab
3.4.
Example crontab formats
3.5.
Usage
4.
Frequently Asked Questions
4.1.
What are the major differences between using at and using crontab?
4.2.
How are different time zones handled?
4.3.
Can one user edit another user's crontab?
5.
Conclusion