Set Up Scheduled Tasks

LinuxLinuxBeginner
Practice Now

Introduction

In this lab, you will learn how to set up scheduled tasks on Linux. You'll explore two powerful tools: the watch command for running commands repeatedly at short intervals, and the crontab utility for scheduling tasks to run at specific times. These skills are essential for system administrators and anyone who needs to automate recurring tasks on a Linux system.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) linux(("`Linux`")) -.-> linux/SystemInformationandMonitoringGroup(["`System Information and Monitoring`"]) linux(("`Linux`")) -.-> linux/InputandOutputRedirectionGroup(["`Input and Output Redirection`"]) linux(("`Linux`")) -.-> linux/PackagesandSoftwaresGroup(["`Packages and Softwares`"]) linux(("`Linux`")) -.-> linux/VersionControlandTextEditorsGroup(["`Version Control and Text Editors`"]) linux/BasicFileOperationsGroup -.-> linux/cat("`File Concatenating`") linux/BasicFileOperationsGroup -.-> linux/tail("`File End Display`") linux/SystemInformationandMonitoringGroup -.-> linux/watch("`Command Repeating`") linux/SystemInformationandMonitoringGroup -.-> linux/crontab("`Job Scheduling`") linux/InputandOutputRedirectionGroup -.-> linux/redirect("`I/O Redirecting`") linux/PackagesandSoftwaresGroup -.-> linux/apt("`Package Handling`") linux/VersionControlandTextEditorsGroup -.-> linux/vim("`Text Editing`") linux/SystemInformationandMonitoringGroup -.-> linux/date("`Date/Time Displaying`") linux/SystemInformationandMonitoringGroup -.-> linux/service("`Service Managing`") subgraph Lab Skills linux/cat -.-> lab-47{{"`Set Up Scheduled Tasks`"}} linux/tail -.-> lab-47{{"`Set Up Scheduled Tasks`"}} linux/watch -.-> lab-47{{"`Set Up Scheduled Tasks`"}} linux/crontab -.-> lab-47{{"`Set Up Scheduled Tasks`"}} linux/redirect -.-> lab-47{{"`Set Up Scheduled Tasks`"}} linux/apt -.-> lab-47{{"`Set Up Scheduled Tasks`"}} linux/vim -.-> lab-47{{"`Set Up Scheduled Tasks`"}} linux/date -.-> lab-47{{"`Set Up Scheduled Tasks`"}} linux/service -.-> lab-47{{"`Set Up Scheduled Tasks`"}} end

Use the watch Command

The watch command allows you to run a command repeatedly and view its output in real-time. This is useful for monitoring changes or running a command at regular short intervals.

  1. Open your terminal. You should be in the /home/labex/project directory. If you're not sure, you can always check your current directory with the pwd command.

  2. We'll use watch to display the current date and time every 5 seconds. Enter the following command:

    watch -n 5 date

    Here's what this command does:

    • watch is the command we're using to repeat another command.
    • -n 5 is an option that tells watch to wait 5 seconds between each execution. If you omit this, watch will use a default interval of 2 seconds.
    • date is the command that watch will run repeatedly. It displays the current date and time.
  3. After entering the command, you should see a full-screen display that updates every 5 seconds. It will look similar to this:

    lab-set-up-scheduled-tasks-1-1.png

    The top line shows the command being run and how often it's updating. The rest of the screen shows the output of the date command.

  4. To exit the watch command, press Ctrl+C. This key combination is commonly used in Linux to terminate a running command.

    If you don't stop the watch command, it will continue running indefinitely, which might prevent you from entering new commands in your terminal.

Install Crontab

Before we can use crontab to schedule tasks, we need to make sure it's installed on our system. Most Linux distributions come with crontab pre-installed, but it's good practice to check and install it if necessary.

  1. First, let's check if crontab is already installed. We can do this by trying to run the crontab command:

    crontab -l

    If crontab is installed, you'll either see a list of your current cron jobs or a message saying "no crontab for labex".

  2. If you see an error message saying the command is not found, we need to install crontab. On Ubuntu or Debian-based systems, we can install it using the following commands:

    sudo apt update
    sudo apt install cron

    You'll be prompted to enter your password. Type it in (note that you won't see any characters as you type for security reasons) and press Enter.

  3. After installation, start the cron service:

    sudo service cron start

    This command starts the cron service immediately.

  4. Now, verify that cron is installed and running:

    sudo service cron status

    You should see output indicating that the cron service is running.

Introduction to Crontab

Now that we have crontab installed, let's explore how to use it. Crontab is used for scheduling tasks at specific times, even when you're not logged in.

  1. First, let's view your current crontab entries (if any). Use the following command:

    crontab -l

    The -l option stands for "list". This command displays all the scheduled tasks in your crontab.

    If you haven't set up any cron jobs yet, you'll see a message saying "no crontab for labex". This is normal for a new user.

  2. Now, let's open the crontab for editing. Use this command:

    crontab -e

    The -e option stands for "edit". This command opens your crontab file in a text editor.

    If this is your first time using crontab, you may be prompted to choose an editor. You'll see a list of numbers corresponding to different editors. For beginners, nano (usually option 1) is a good choice because it's simpler to use. Type the number for nano and press Enter.

    Selecting an editor

    If you're not prompted to choose an editor, don't worry. It means a default editor has already been set up for you.

  3. Once the editor opens, you'll see an empty file (or any existing cron jobs if you had any). Don't add anything yet; we'll do that in a later step. For now, just familiarize yourself with the editor.

    If you're using nano, you'll see some help commands at the bottom of the screen. The ^ symbol represents the Ctrl key. So ^X means "Ctrl+X", which is used to exit nano.

  4. Exit the editor without making any changes. In nano, you can do this by pressing Ctrl+X. If you're asked if you want to save changes, press 'N' for No.

Understanding Crontab Syntax

Before we add a cron job, it's crucial to understand the syntax. Crontab uses a specific format to determine when a task should run.

  1. The basic format of a cron job is:

    * * * * * command_to_execute

    Each asterisk represents a specific time unit, from left to right:

    1. Minute (0-59)
    2. Hour (0-23)
    3. Day of the month (1-31)
    4. Month (1-12)
    5. Day of the week (0-7, where both 0 and 7 represent Sunday)
  2. Here are some examples to help you understand:

    • 30 2 * * * means "At 2:30 AM, every day"
    • 0 9 * * 1-5 means "At 9:00 AM, Monday through Friday"
    • */15 * * * * means "Every 15 minutes"
  3. You can use the following special characters:

    • *: any value
    • ,: value list separator
    • -: range of values
    • /: step values
  4. Let's break down a more complex example:
    15,45 9-17 * * 1-5 /path/to/script.sh
    This means: "Run /path/to/script.sh at 15 and 45 minutes past every hour from 9 AM to 5 PM, Monday to Friday"

Understanding this syntax is key to creating effective cron jobs. Take some time to think about how you might schedule different tasks using this format.

Add a Cron Job

Now that we understand the syntax, let's add a simple cron job that writes the current date to a file every minute.

  1. Open your crontab for editing:

    crontab -e
  2. Once the editor opens, add the following line to your crontab:

    * * * * * date >> /home/labex/project/date_log.txt
    alt text

    Let's break this down:

    • The five asterisks * * * * * mean "every minute of every hour of every day of every month and every day of the week".
    • date is the command we're running.
    • >> is used to append the output to a file (instead of overwriting it).
    • /home/labex/project/date_log.txt is the file where we're storing the output.
  3. Save and exit the editor. If you're using nano:

    • Press Ctrl+X to exit
    • Press Y to confirm that you want to save changes
    • Press Enter to confirm the file name
  4. After you exit, you should see a message saying "crontab: installing new crontab". This confirms that your changes have been saved.

Monitor Your Cron Job

Now that we've set up a cron job, let's check if it's working correctly.

  1. First, we need to wait for at least one minute after adding the cron job. This is because cron jobs run on the minute, so it may take up to a minute for your job to run for the first time.

  2. After waiting, use the cat command to view the contents of the log file:

    cat /home/labex/project/date_log.txt

    The cat command displays the contents of a file directly in the terminal.

  3. You should see at least one line with a date and time. It will look something like this:

    Sat Aug  5 10:15:01 UTC 2023

    If you don't see anything, wait another minute and try again. Sometimes it can take a moment for the cron job to start running.

  4. To see the cron job in action, you can use the watch command we learned earlier to monitor the file in real-time:

    watch -n 60 cat /home/labex/project/date_log.txt

    This will update every 60 seconds, showing you the new entries as they're added.

  5. Let this run for a few minutes. You should see a new line added each minute.

  6. When you're done observing, press Ctrl+C to exit the watch command.

Summary

Congratulations! You've successfully completed the "Set Up Scheduled Tasks" lab. You've learned how to:

  1. Use the watch command to run commands repeatedly at short intervals.
  2. Install and set up crontab on your system.
  3. View and edit your crontab using crontab -l and crontab -e.
  4. Understand crontab syntax for scheduling tasks.
  5. Create a simple cron job that runs every minute.
  6. Monitor the output of your cron job.

These skills are fundamental for automating tasks and monitoring systems in Linux environments. As you continue your Linux journey, you'll find many more uses for scheduled tasks in system administration and automation.

Remember, while we used a simple example of logging the date, you can use cron jobs for more complex tasks like backing up data, updating software, or running system maintenance scripts. Always be careful when setting up cron jobs, especially if they involve system-critical operations.

Other Linux Tutorials you may like