Skip to main content

Scheduling system tasks

Scheduling system tasks is an essential part of system administration and automation. It allows you to automate repetitive tasks, perform maintenance, and execute scripts or commands at specific times or intervals.

1. Using cron for Scheduled Tasks:

cron is a time-based job scheduler on Unix-like operating systems. It allows you to specify when and how often tasks should run. Here's how to use it:

a. The crontab Command:

  1. Open your terminal.

  2. To edit your user-specific cron jobs, use:

    crontab -e
  3. To edit the system-wide cron jobs (requires root privileges), use:

    sudo crontab -e

b. crontab Syntax:

The crontab file uses a specific syntax to define when and what tasks should run. The syntax consists of five fields followed by the command to be executed:

* * * * * command_to_execute
- - - - -
| | | | |
| | | | +----- Day of the week (0 - 7) (Sunday is both 0 and 7)
| | | +------- Month (1 - 12)
| | +--------- Day of the month (1 - 31)
| +----------- Hour (0 - 23)
+------------- Minute (0 - 59)

c. Examples of cron Jobs:

  • To run a script every day at 2:30 PM:

    30 14 * * * /path/to/script.sh
  • To run a command every Monday at 3:00 AM:

    0 3 * * 1 /path/to/command
  • To run a script every 15 minutes:

    */15 * * * * /path/to/script.sh

d. Managing cron Jobs:

  • To list your current cron jobs:

    crontab -l
  • To remove all your cron jobs:

    crontab -r

2. Using at for One-Time Tasks:

The at command allows you to schedule tasks to run only once at a specific time. Here's how to use it:

a. The at Command:

  1. Open your terminal.

  2. To schedule a task, use the at command followed by the time when you want the task to run:

    at <time>

    For example:

    at 2:30 PM
  3. You'll enter an interactive mode where you can input the command(s) to run. Type Ctrl+D to finish entering commands.

b. Examples of at Jobs:

  • To run a script at a specific time (e.g., 3:45 PM):

    at 3:45 PM

    Then, enter the command(s) to execute.

  • To run a command at midnight:

    at midnight
  • To run a command tomorrow at a specific time (e.g., 8:00 AM):

    at tomorrow 8:00 AM

c. Managing at Jobs:

  • To list your pending at jobs:

    atq
  • To remove a specific at job (replace job_number with the job ID from atq):

    atrm <job_number>
  • To remove all your at jobs:

    at -r

Scheduling system tasks using cron and at can greatly simplify the automation of routine tasks and maintenance, making your system administration more efficient and reliable.