Build a Task Scheduler Using Bash

LinuxLinuxBeginner
Practice Now

Introduction

This project will guide you through creating a task scheduler using a Bash script. The task scheduler allows you to schedule and manage tasks to be executed at specified intervals, such as hourly, daily, or weekly. The script provides options to list scheduled tasks, add new tasks, and remove existing tasks.

👀 Preview

Alt text

To get started, you'll need to create a file named task_scheduler.sh and write the provided code in it. Let's proceed to the first step.

🎯 Tasks

In this project, you will learn:

  • How to create the project files
  • How to add code to display scheduled tasks
  • How to add code to add a new task
  • How to add code to remove a task
  • How to set up the main menu loop
  • How to make the script executable
  • How to run the project

🏆 Achievements

After completing this project, you will be able to:

  • Create a Bash script
  • Use crontab to schedule tasks
  • Prompt user input in Bash script
  • Add and remove tasks from crontab
  • Create a menu loop in Bash script
  • Make a Bash script executable and run it

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/SystemInformationandMonitoringGroup(["`System Information and Monitoring`"]) linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/InputandOutputRedirectionGroup(["`Input and Output Redirection`"]) linux(("`Linux`")) -.-> linux/PackagesandSoftwaresGroup(["`Packages and Softwares`"]) linux(("`Linux`")) -.-> linux/TextProcessingGroup(["`Text Processing`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux(("`Linux`")) -.-> linux/UserandGroupManagementGroup(["`User and Group Management`"]) linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) shell(("`Shell`")) -.-> shell/BasicSyntaxandStructureGroup(["`Basic Syntax and Structure`"]) shell(("`Shell`")) -.-> shell/VariableHandlingGroup(["`Variable Handling`"]) shell(("`Shell`")) -.-> shell/ControlFlowGroup(["`Control Flow`"]) shell(("`Shell`")) -.-> shell/AdvancedScriptingConceptsGroup(["`Advanced Scripting Concepts`"]) shell(("`Shell`")) -.-> shell/SystemInteractionandConfigurationGroup(["`System Interaction and Configuration`"]) linux/SystemInformationandMonitoringGroup -.-> linux/crontab("`Job Scheduling`") linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") linux/InputandOutputRedirectionGroup -.-> linux/pipeline("`Data Piping`") linux/InputandOutputRedirectionGroup -.-> linux/redirect("`I/O Redirecting`") linux/BasicSystemCommandsGroup -.-> linux/read("`Input Reading`") linux/PackagesandSoftwaresGroup -.-> linux/apt("`Package Handling`") linux/TextProcessingGroup -.-> linux/grep("`Pattern Searching`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") linux/UserandGroupManagementGroup -.-> linux/sudo("`Privilege Granting`") linux/BasicFileOperationsGroup -.-> linux/touch("`File Creating/Updating`") linux/BasicFileOperationsGroup -.-> linux/chmod("`Permission Modifying`") shell/BasicSyntaxandStructureGroup -.-> shell/shebang("`Shebang`") shell/BasicSyntaxandStructureGroup -.-> shell/comments("`Comments`") shell/BasicSyntaxandStructureGroup -.-> shell/quoting("`Quoting Mechanisms`") shell/VariableHandlingGroup -.-> shell/variables_decl("`Variable Declaration`") shell/VariableHandlingGroup -.-> shell/variables_usage("`Variable Usage`") shell/ControlFlowGroup -.-> shell/case("`Case Statements`") shell/ControlFlowGroup -.-> shell/while_loops("`While Loops`") shell/ControlFlowGroup -.-> shell/exit_status("`Exit and Return Status`") shell/AdvancedScriptingConceptsGroup -.-> shell/read_input("`Reading Input`") shell/AdvancedScriptingConceptsGroup -.-> shell/subshells("`Subshells and Command Groups`") shell/AdvancedScriptingConceptsGroup -.-> shell/adv_redirection("`Advanced Redirection`") shell/SystemInteractionandConfigurationGroup -.-> shell/globbing_expansion("`Globbing and Pathname Expansion`") linux/FileandDirectoryManagementGroup -.-> linux/wildcard("`Wildcard Character`") subgraph Lab Skills linux/crontab -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} linux/echo -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} linux/pipeline -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} linux/redirect -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} linux/read -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} linux/apt -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} linux/grep -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} linux/cd -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} linux/sudo -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} linux/touch -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} linux/chmod -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} shell/shebang -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} shell/comments -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} shell/quoting -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} shell/variables_decl -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} shell/variables_usage -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} shell/case -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} shell/while_loops -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} shell/exit_status -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} shell/read_input -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} shell/subshells -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} shell/adv_redirection -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} shell/globbing_expansion -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} linux/wildcard -.-> lab-298846{{"`Build a Task Scheduler Using Bash`"}} end

Create the project files

Create a new file named task_scheduler.sh using a text editor of your choice. You can use the following command to create the file:

cd ~/project
touch task_scheduler.sh

Now open the file in your text editor.

Add code to display scheduled tasks

Install crontab if it is not already installed on your system. To install crontab, run the following command in the terminal:

sudo apt-get install cron

Inside the task_scheduler.sh file, add the following code:

#!/bin/bash

## Function to display the scheduled tasks
list_tasks() {
  echo "Scheduled tasks:"
  crontab -l
  echo
}

This code defines a function named list_tasks, which displays the scheduled tasks using the crontab -l command.

Add code to add a new task

Below the previously added code, add the following code:

## Function to add a new task
add_task() {
  read -p "Enter the command or script to be executed: " command
  read -p "Enter the schedule (hourly, daily, weekly): " schedule
  read -p "Enter any additional parameters: " parameters

  case $schedule in
    hourly)
      cron_schedule="0 * * * *"
      ;;
    daily)
      cron_schedule="0 0 * * *"
      ;;
    weekly)
      cron_schedule="0 0 * * 0"
      ;;
    *)
      echo "Invalid schedule. Please choose hourly, daily, or weekly."
      return
      ;;
  esac

  ## Add the task to the crontab
  (
    crontab -l 2> /dev/null
    echo "$cron_schedule $command $parameters"
  ) | crontab -

  echo "Task scheduled successfully."
  echo
}

This code defines a function named add_task, which prompts the user to enter the command or script to be executed, the schedule (hourly, daily, or weekly), and any additional parameters. It then sets the appropriate cron schedule based on the chosen schedule. Finally, it adds the task to the crontab using the crontab -l command.

Add code to remove a task

Below the previously added code, add the following code:

## Function to remove a task
remove_task() {
  read -p "Enter the command or script to be removed: " command

  ## Remove the task from the crontab
  crontab -l | grep -v "$command" | crontab -

  echo "Task removed successfully."
  echo
}

This code defines a function named remove_task, which prompts the user to enter the command or script to be removed. It then removes the task from the crontab using the crontab -l command.

Below the previously added code, add the following code:

## Main menu loop
while true; do
  echo "Task Scheduler"
  echo "1. List scheduled tasks"
  echo "2. Add a task"
  echo "3. Remove a task"
  echo "4. Exit"
  read -p "Enter your choice: " choice
  echo

  case $choice in
    1)
      list_tasks
      ;;
    2)
      add_task
      ;;
    3)
      remove_task
      ;;
    4)
      break
      ;;
    *)
      echo "Invalid choice. Please try again."
      echo
      ;;
  esac
done

This code sets up a main menu loop that repeatedly displays a menu and prompts the user for their choice. Based on the chosen option, it calls the corresponding function (list_tasks, add_task, or remove_task) or exits the loop.

Save and close the file

Save the changes to the task_scheduler.sh file and close the text editor.

To make the script executable, run the following command in the terminal:

chmod +x task_scheduler.sh

This command sets the execute permission for the task_scheduler.sh file.

Run the project

To run the task scheduler, execute the following command in the terminal:

./task_scheduler.sh

This command runs the task_scheduler.sh script and starts the task scheduler. Follow the on-screen instructions to list scheduled tasks, add new tasks, or remove existing tasks.

Alt text

Summary

Congratulations! You have successfully completed the task scheduler project. You created a Bash script that allows you to schedule and manage tasks. The script provides options to list scheduled tasks, add new tasks, and remove existing tasks. Feel free to customize the script further to fit your specific needs. Happy scheduling!

Other Linux Tutorials you may like