Scheduling and Automation

Level: Intermediate Module: Linux Fundamentals 6 min read Lesson 9 of 10

Overview

  • What you’ll learn: How to schedule and automate recurring tasks using cron, systemd timers, the at command, logrotate, and anacron.
  • Prerequisites: Lesson 8 – Storage and Logical Volume Management
  • Estimated reading time: 17 minutes

Introduction

Automation is a cornerstone of effective system administration. Rather than manually performing routine tasks like backups, log rotation, and system updates, Linux provides several scheduling mechanisms that execute tasks automatically at specified times or intervals.

In this lesson, you will learn the traditional cron scheduler, modern systemd timers, the one-time at command, and the logrotate utility. Mastering these tools will help you build reliable, hands-off server management workflows.

Cron

Cron is the traditional Unix task scheduler. It runs as a daemon and checks its configuration every minute for tasks to execute.

Cron Syntax

A cron schedule consists of five time fields followed by the command to run:

# ┌───────────── minute (0-59)
# │ ┌───────────── hour (0-23)
# │ │ ┌───────────── day of month (1-31)
# │ │ │ ┌───────────── month (1-12)
# │ │ │ │ ┌───────────── day of week (0-7, 0 and 7 = Sunday)
# │ │ │ │ │
# * * * * * command to execute

# Examples:
0 2 * * *     /usr/local/bin/backup.sh      # Daily at 2:00 AM
*/15 * * * *  /usr/local/bin/check-health.sh # Every 15 minutes
0 0 * * 0     /usr/local/bin/weekly-report.sh # Sunday at midnight
30 6 1 * *   /usr/local/bin/monthly-audit.sh  # 1st of month at 6:30 AM
0 */4 * * 1-5 /usr/local/bin/workday-task.sh  # Every 4 hours on weekdays

User Crontab

$ crontab -e                           # Edit your crontab
$ crontab -l                           # List your crontab
$ crontab -r                           # Remove your crontab
$ sudo crontab -u www-data -e          # Edit another user's crontab

System Crontab

System-wide cron jobs are stored in /etc/crontab and /etc/cron.d/. These include an extra field for the user:

$ cat /etc/crontab
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
17 * * * *  root  cd / && run-parts --report /etc/cron.hourly
25 6 * * *  root  test -x /usr/sbin/anacron || run-parts --report /etc/cron.daily
47 6 * * 7  root  test -x /usr/sbin/anacron || run-parts --report /etc/cron.weekly
52 6 1 * *  root  test -x /usr/sbin/anacron || run-parts --report /etc/cron.monthly

Drop-in directories provide a convenient way to add scripts without editing crontab files:

  • /etc/cron.hourly/ — Scripts run every hour.
  • /etc/cron.daily/ — Scripts run once a day.
  • /etc/cron.weekly/ — Scripts run once a week.
  • /etc/cron.monthly/ — Scripts run once a month.

systemd Timers

systemd timers are the modern alternative to cron, offering more features like dependency management, logging integration with journalctl, and precise calendar expressions.

Creating a Timer

A systemd timer requires two unit files: a .service file and a .timer file:

# /etc/systemd/system/backup.service
[Unit]
Description=Daily backup job

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
User=root

# /etc/systemd/system/backup.timer
[Unit]
Description=Run backup daily at 2:00 AM

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true

[Install]
WantedBy=timers.target
$ sudo systemctl daemon-reload
$ sudo systemctl enable --now backup.timer

$ systemctl list-timers --all
NEXT                        LEFT          LAST                        PASSED    UNIT
Mon 2024-01-15 02:00:00 UTC 13h left      Sun 2024-01-14 02:00:00 UTC 10h ago  backup.timer

OnCalendar Syntax

OnCalendar=hourly                     # Every hour
OnCalendar=daily                      # Every day at midnight
OnCalendar=weekly                     # Every Monday at midnight
OnCalendar=*-*-* 06:00:00             # Daily at 6:00 AM
OnCalendar=Mon-Fri *-*-* 09:00:00     # Weekdays at 9:00 AM
OnCalendar=*-*-01 00:00:00            # First of every month

$ systemd-analyze calendar "Mon-Fri *-*-* 09:00:00"  # Test expression

The at Command

at schedules a one-time command to run at a specific time:

$ echo "/usr/local/bin/deploy.sh" | at 3:00 AM
job 1 at Mon Jan 15 03:00:00 2024

$ echo "/usr/local/bin/report.sh" | at now + 2 hours
job 2 at Mon Jan 15 15:30:00 2024

$ atq                                  # List pending jobs
1    Mon Jan 15 03:00:00 2024 a admin
2    Mon Jan 15 15:30:00 2024 a admin

$ atrm 2                               # Remove a pending job

Logrotate

logrotate automatically rotates, compresses, and removes old log files to prevent disk exhaustion:

$ cat /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid)
    endscript
}

$ sudo logrotate -d /etc/logrotate.conf   # Dry run (debug mode)
$ sudo logrotate -f /etc/logrotate.conf   # Force rotation now

Anacron

anacron is designed for machines that are not running 24/7. Unlike cron, anacron ensures that scheduled tasks are executed even if the machine was off at the scheduled time:

$ cat /etc/anacrontab
# period  delay  job-id          command
1         5      cron.daily      run-parts /etc/cron.daily
7         10     cron.weekly     run-parts /etc/cron.weekly
@monthly  15     cron.monthly    run-parts /etc/cron.monthly

Key Takeaways

  • Cron uses a five-field time specification (minute, hour, day, month, weekday) and runs tasks on a schedule.
  • User crontabs are managed with crontab -e; system crontabs live in /etc/crontab and /etc/cron.d/.
  • systemd timers provide a modern alternative with better logging, dependency management, and calendar expressions.
  • The at command schedules one-time tasks; use atq to list and atrm to remove.
  • logrotate manages log file rotation and compression to prevent disk exhaustion.
  • anacron ensures tasks run even if the system was powered off at the scheduled time.

What’s Next

In Lesson 10, you will learn about the Kernel and Boot Process — how Linux boots from BIOS/UEFI through GRUB to the kernel and systemd, and how to manage kernel modules.

繁體中文

概述

  • 學習目標:學習如何使用 cron、systemd 計時器、at 命令、logrotate 和 anacron 來排程和自動化循環任務。
  • 先決條件:第 8 課 – 儲存和邏輯卷管理
  • 預計閱讀時間:17 分鐘

簡介

自動化是有效系統管理的基石。Linux 提供了多種排程機制,可在指定時間或間隔自動執行備份、日誌輪替和系統更新等例行任務。

Cron

Cron 是傳統的 Unix 任務排程器。它作為守護行程運行,每分鐘檢查其設定以執行任務。

Cron 語法

# 分鐘 小時 日 月 星期幾 命令
0 2 * * *     /usr/local/bin/backup.sh      # 每天凌晨 2:00
*/15 * * * *  /usr/local/bin/check-health.sh # 每 15 分鐘
0 0 * * 0     /usr/local/bin/weekly-report.sh # 每週日午夜

使用者 Crontab

$ crontab -e                           # 編輯您的 crontab
$ crontab -l                           # 列出您的 crontab

系統 Crontab

系統級 cron 任務儲存在 /etc/crontab/etc/cron.d/。Drop-in 目錄(/etc/cron.daily//etc/cron.weekly/ 等)提供了便利的方式來新增腳本。

systemd 計時器

systemd 計時器是 cron 的現代替代方案,提供更多功能如相依性管理和與 journalctl 的日誌整合。

$ sudo systemctl enable --now backup.timer
$ systemctl list-timers --all          # 列出所有計時器

at 命令

at 排程一次性命令在特定時間執行:

$ echo "/usr/local/bin/deploy.sh" | at 3:00 AM
$ atq                                  # 列出待處理的任務
$ atrm 2                               # 移除待處理的任務

Logrotate

logrotate 自動輪替、壓縮和移除舊日誌檔案以防止磁碟耗盡。

Anacron

anacron 專為非全天候運行的機器設計。與 cron 不同,anacron 確保即使機器在排程時間關閉,任務也會被執行。

重點摘要

  • Cron 使用五欄位時間規格(分鐘、小時、日、月、星期幾)按排程執行任務。
  • 使用 crontab -e 管理使用者 crontab;系統 crontab 位於 /etc/crontab/etc/cron.d/
  • systemd 計時器提供現代替代方案,具有更好的日誌記錄和日曆表達式。
  • at 排程一次性任務;atq 列出,atrm 移除。
  • logrotate 管理日誌檔案輪替和壓縮。
  • anacron 確保即使系統在排程時間關閉也能執行任務。

下一步

在第 10 課中,您將學習核心和開機流程——Linux 如何從 BIOS/UEFI 經由 GRUB 到核心和 systemd 的開機過程,以及如何管理核心模組。

日本語

概要

  • 学習内容:cron、systemd タイマー、at コマンド、logrotate、anacron を使用した定期タスクのスケジューリングと自動化。
  • 前提条件:レッスン8 – ストレージと論理ボリューム管理
  • 推定読了時間:17分

はじめに

自動化は効果的なシステム管理の礎です。Linux はバックアップ、ログローテーション、システム更新などの定期的なタスクを指定された時間や間隔で自動的に実行する複数のスケジューリングメカニズムを提供します。

Cron

Cron は伝統的な Unix タスクスケジューラーです。デーモンとして実行され、毎分設定をチェックして実行すべきタスクを探します。

Cron 構文

# 分 時 日 月 曜日 コマンド
0 2 * * *     /usr/local/bin/backup.sh      # 毎日午前2:00
*/15 * * * *  /usr/local/bin/check-health.sh # 15分ごと
0 0 * * 0     /usr/local/bin/weekly-report.sh # 毎週日曜日の深夜

ユーザー Crontab

$ crontab -e                           # crontab を編集
$ crontab -l                           # crontab を一覧表示

システム Crontab

システム全体の cron ジョブは /etc/crontab/etc/cron.d/ に保存されます。ドロップインディレクトリ(/etc/cron.daily//etc/cron.weekly/ など)でスクリプトを簡単に追加できます。

systemd タイマー

systemd タイマーは cron の最新の代替手段で、依存関係管理や journalctl とのログ統合など、より多くの機能を提供します。

$ sudo systemctl enable --now backup.timer
$ systemctl list-timers --all          # すべてのタイマーを一覧表示

at コマンド

at は一度限りのコマンドを特定の時間に実行するようスケジュールします:

$ echo "/usr/local/bin/deploy.sh" | at 3:00 AM
$ atq                                  # 保留中のジョブを一覧表示
$ atrm 2                               # 保留中のジョブを削除

Logrotate

logrotate はログファイルのローテーション、圧縮、古いログの削除を自動的に行い、ディスクの枯渇を防ぎます。

Anacron

anacron は24時間稼働していないマシン向けに設計されています。cron と異なり、anacron はマシンがスケジュール時間にオフだった場合でもタスクが実行されることを保証します。

重要ポイント

  • Cron は5フィールドの時間指定(分、時、日、月、曜日)でタスクをスケジュール実行。
  • crontab -e でユーザー crontab を管理。システム crontab は /etc/crontab/etc/cron.d/
  • systemd タイマーはより良いログ記録とカレンダー式を備えた最新の代替手段。
  • at で一度限りのタスクをスケジュール。atq で一覧、atrm で削除。
  • logrotate はログファイルのローテーションと圧縮を管理。
  • anacron はシステムがスケジュール時にオフだった場合でもタスク実行を保証。

次のステップ

レッスン10では、カーネルとブートプロセスについて学びます。BIOS/UEFI から GRUB を経てカーネルと systemd に至る Linux のブート過程、およびカーネルモジュールの管理方法を学びます。

You Missed