Scheduling Tasks with Cron
# CHAPTER 13
Scheduling Tasks with Cron
1. Introduction
A meticulously crafted log-cleaning script is entirely useless if the systems administrator forgets to run it on Friday evening. The ultimate objective of DevOps scripting is the complete removal of the human element. In Unix, the supreme orchestrator of time is a permanent background daemon calledcron. It runs silently 24 hours a day, checking a master schedule every 60 seconds. If a task is scheduled for that exact minute, cron executes your shell script flawlessly without human intervention. In this chapter, we will master the cryptic 5-field syntax of the crontab file, schedule scripts to run daily, weekly, or upon server reboot, and conquer the unique environmental constraints of scripts executed by the cron daemon.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Access and edit the user-specific cron schedule using
crontab -e.
- Decipher and author the 5-field cron time syntax (Minute, Hour, Day, Month, DayOfWeek).
- Schedule a shell script to execute at specific, recurring periodic intervals.
- Route standard output and standard error from a cron job into a permanent log file.
-
Understand and mitigate the restricted
$PATHlimitations inherent to the cron environment.
3. The crontab File
Every user on a Unix system possesses their own personal scheduling file, known as a crontab (Cron Table).
To edit your schedule, you execute:
*(Note: If prompted, press 1 to select the nano text editor).*
To simply view your schedule without risking accidental edits, type crontab -l (list).
4. Cron Syntax (The 5 Stars)
A cron job entry consists of 5 asterisks (*) followed by the absolute pathway to the script you wish to execute.
The five fields represent:
[Minute] [Hour] [DayofMonth] [Month] [DayofWeek]
-
An asterisk
*signifies "Every".
- Hours are calculated in 24-hour military time (0 = Midnight, 23 = 11 PM).
- Day of Week ranges from 0-7 (where both 0 and 7 represent Sunday).
Standard Examples:
Advanced Syntax Modifiers:
-
Step Values (
/): Run a script every 15 minutes:*/15 * * * *
-
Multiple Values (
,): Run at 1:00 AM and 1:00 PM:0 1,13 * * *
-
Upon Reboot (
@reboot): Run a script exactly once when the server boots up:@reboot /home/admin/startup.sh
5. Managing Cron Output (Logging)
If you run./backup.sh manually, the text Backup Successful prints to your screen.
When cron executes ./backup.sh at 3:00 AM, you are asleep. There is no screen.
If you do not explicitly redirect the output using the tools learned in Chapter 9, cron will attempt to email the output to a local mailbox (which is usually unconfigured) and the data vanishes forever.
You must redirect cron output into a dedicated log file!
6. The Cron Environment Trap
This is the #1 reason why a shell script works perfectly for a human, but fails catastrophically when executed bycron.
When you log in, your profile loads your customized $PATH variables (allowing you to simply type commands like tar or docker).
When cron wakes up, it operates in a stripped-down, bare-bones environment. It does not load your profile. If your script uses a custom tool, cron will not be able to locate it, and the script will silently crash.
The Fix: Inside your shell script, ALWAYS utilize absolute paths for critical commands or files.
-
*Bad Practice:*
tar -czvf backup.tar /data
-
*Professional Practice:*
/usr/bin/tar -czvf /tmp/backup.tar /data
7. Diagrams/Visual Suggestions
*Visual Concept: The Cron Time Map* Create a visual translation of the string30 14 * * 1.
Draw five sequential boxes.
-
Box 1:
30(Label below: Minute, 0-59).
-
Box 2:
14(Label below: Hour, 0-23).
-
Box 3:
*(Label below: Day of Month, 1-31).
-
Box 4:
*(Label below: Month, 1-12).
-
Box 5:
1(Label below: Day of Week, 0-7, Sun-Sun).
8. Best Practices
-
Use
crontab.guru: Do not attempt to guess complex cron syntax in your head. Professional DevOps engineers routinely use the website *crontab.guru* to type out their asterisks and verify the English translation before committing it to a production server schedule.
9. Common Mistakes
-
Forgetting execute permissions:
cronis not magic; it is bound by standard Unix file permissions. If you add/home/admin/script.shto your crontab, but you forgot to executechmod +x script.sh,cronwill silently fail to execute the file every single time it tries.
10. Mini Project: Create an Automated Cleanup Script
Let's build a script that deletes temporary log files older than 7 days, and schedule it to run every Sunday at midnight.-
1.
nano log_cleanup.sh
- 2. Write the code:
-
3.
Make it executable:
chmod +x logcleanup.sh
-
4.
Open your schedule:
crontab -e
- 5. Add the job (Run at 00:00 every Sunday/Day 0):
0 0 * * 0 /path/to/logcleanup.sh >> /var/log/cleanup.log 2>&1
- 6. Save and exit. The system is now permanently automated.
11. Practice Exercises
- 1. Translate the following English requirement into exact Cron syntax: "Execute the database synchronization script exactly at 3:15 AM every weekday (Monday through Friday)."
-
2.
Explain the "Cron Environment Trap". Why might a script containing the command
aws s3 syncexecute flawlessly when typed interactively by an administrator, but fail with "Command not found" when executed by cron?
12. MCQs with Answers
An administrator edits their crontab file and inputs the schedule string */5 * * * *. How often will the associated shell script execute?
When scheduling an automation script via cron, which redirection syntax is considered a mandatory best practice to ensure that both successful script outputs and catastrophic runtime errors are permanently recorded for forensic analysis?
13. Interview Questions
-
Q: A developer complains that a cron job they scheduled using
crontab -eis failing to run. You verify the syntax is perfectly formatted as0 5 * * * /opt/scripts/deploy.sh. Walk me through the two most common administrative oversights that cause a perfectly scheduled script to fail execution. *(Hint: Permissions and Paths).*
- Q: Explain the structural syntax of the cron schedule string. If you needed a script to run ONLY during normal business hours (9:00 AM to 5:00 PM) on weekends (Saturday and Sunday), how would you construct the hour and day fields?
-
Q: Contrast the
@rebootcron directive with managing a script via asystemdservice file. While both can start a script on boot, why issystemdvastly superior for running permanent background web servers?
14. FAQs
Q: Can I run a cron job every 10 seconds? A: No. The cron daemon only checks its schedule once per minute. Minute* is the absolute minimum granularity. If you require a script to execute every 10 seconds, you must write a standard while true loop inside a script utilizing a sleep 10 command, and run that script permanently in the background.
15. Summary
In Chapter 13, we delegated absolute execution authority to the Unix operating system. We interfaced with thecron daemon via crontab -e, mastering the strict 5-field asterisk syntax to orchestrate precise time-based execution schedules. We secured our automated pipelines by redirecting disjointed stdout and stderr streams directly into persistent log files utilizing the >> log 2>&1 technique. Finally, we recognized and mitigated the environmental constraints of the cron daemon, strictly utilizing absolute execution paths to ensure our scripts execute flawlessly in the absence of a user's interactive profile variables.