> For the complete documentation index, see [llms.txt](https://riteshs4hu.gitbook.io/infosec-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://riteshs4hu.gitbook.io/infosec-notes/linux-server-administrator/task-schedule.md).

# Task Schedule

Task scheduling in Linux is primarily managed using **cron jobs**, which allow users to automate commands or scripts at specified intervals.

***

### Viewing Scheduled Tasks

#### `crontab` - Manage Cron Jobs

* List current user’s scheduled cron jobs:

  ```sh
  crontab -l
  ```
* Edit the current user’s cron jobs:

  ```sh
  crontab -e
  ```
* Remove all cron jobs for the current user:

  ```sh
  crontab -r
  ```
* List system-wide cron jobs:

  ```sh
  sudo cat /etc/crontab
  ```

***

### Understanding Crontab Files

There are different types of crontab files:

1. **User Crontabs**: Each user has their own crontab file, managed using `crontab` commands.
2. **System Crontab**: Found at `/etc/crontab`, used for system-wide scheduled tasks.
3. **Cron Directories**: Additional system-level cron jobs are placed in:
   * `/etc/cron.hourly/` - Jobs placed in this directory execute every hour.
   * `/etc/cron.daily/` - Jobs here run once every day.
   * `/etc/cron.weekly/` - Tasks in this directory execute once a week.
   * `/etc/cron.monthly/` - Scripts in this folder run once per month.
   * `/etc/cron.d/` - This directory contains custom system-wide cron jobs, where administrators can define scheduled tasks with specific user privileges.

***

### Creating Cron Jobs

Cron jobs follow this format:

```
* * * * * command-to-execute
│ │ │ │ │
│ │ │ │ └── Day of the week (0 - 7, Sunday=0 or 7)
│ │ │ └──── Month (1 - 12)
│ │ └────── Day of the month (1 - 31)
│ └──────── Hour (0 - 23)
└────────── Minute (0 - 59)
```

#### Special Time Expressions

Crontab allows shorthand scheduling:

* `@reboot` – Runs once at startup
* `@hourly` – Runs every hour
* `@daily` – Runs once per day
* `@weekly` – Runs once per week
* `@monthly` – Runs once per month
* `@yearly` – Runs once per year

#### Examples

* Run a script every day at 3:30 AM:

  ```sh
  30 3 * * * /path/to/script.sh
  ```
* Execute a command every Monday at noon:

  ```sh
  0 12 * * 1 /usr/bin/example-command
  ```
* Run a job every 5 minutes:

  ```sh
  */5 * * * * /path/to/task.sh
  ```
* Clear log files at midnight on the first day of every month:

  ```sh
  0 0 1 * * rm -rf /var/log/*.log
  ```

***

### Example Cron Jobs

* Run a script every day at 3:30 AM:

  ```sh
  30 3 * * * /path/to/script.sh
  ```
* Execute a command every Monday at noon:

  ```sh
  0 12 * * 1 /usr/bin/example-command
  ```
* Run a job every 5 minutes:

  ```sh
  */5 * * * * /path/to/task.sh
  ```
* Clear log files at midnight on the first day of every month:

  ```sh
  0 0 1 * * rm -rf /var/log/*.log
  ```
