NANDHOO.

Chapter 12: Automation

Automation is the practice of scheduling tasks to run without human intervention. In the Linux world, this is primarily achieved using Cron, but modern systems also leverage Systemd Timers for more advanced logging and dependency management.

I. Scheduling with Cron

The Cron daemon is a background process that runs continuously and checks every minute for tasks scheduled in the crontab (cron table).

1. Crontab Management

  • crontab -e: Edit your personal crontab.
  • crontab -l: List your scheduled tasks.
  • sudo crontab -u username -e: Edit another user's crontab (root only).

2. The Cron Schedule Syntax

0 2 * * 1MINHOURDAYMONTHWEEKDAY/usr/bin/backup.sh

Key Rules:

  • Use * for "every."
  • Use */15 for "every 15."
  • Use 1,3,5 for "on these specific units."
  • Use 1-5 for "range."

II. Handling Output and Logging

Cron jobs run in a limited environment without a display. If a script produces output, Cron will attempt to email it to the local user. To avoid this and maintain visibility, you should always log output to a file.

# Standard logging pattern
0 2 * * * /home/jane/bin/backup.sh >> /var/log/backups.log 2>&1
  • >>: Appends standard output.
  • 2>&1: Merges errors into the same log file.

III. Anacron: For Laptops and Desktop PC

If your computer is turned off at 2:00 AM, a standard Cron job for that time will never run. Anacron solves this by checking if a task was missed and running it as soon as the system boots up.

  • Configured in /etc/anacrontab.
  • Only works for daily, weekly, or monthly intervals (not minutes/hours).

IV. The Modern Way: Systemd Timers

Most modern Linux distributions (Ubuntu 16.04+, RHEL 7+) use Systemd Timers instead of Cron for system tasks.

Why use Systemd Timers?

  1. Detailed Logs: View output via journalctl -u mytask.timer.
  2. Dependencies: Ensure a task only runs if the network is up.
  3. Resource Control: Use Cgroups to limit the memory or CPU a task can use.

Basic Setup:

Requires two files in /etc/systemd/system/:

  1. mytask.service: Describes what to run.
  2. mytask.timer: Describes when to run.

V. Automation Security

  1. Absolute Paths: Always use /usr/bin/python3 instead of python3 in cron jobs.
  2. User Privileges: Run tasks as the least privileged user possible. Avoid running everything as root.
  3. Locking: Use flock to prevent multiple instances of the same script from running if the previous one is still active.
    • * * * * * flock -n /tmp/my.lock /home/user/script.sh.

In the next chapter, we'll dive into Advanced Scripting techniques to make your code bulletproof.