Scheduling Jobs with cron
The shop's backups and reports still depend on someone remembering to run them. You will put them on a schedule with cron, fix the nightly report that "works when I run it" but never produces anything on schedule, and remove a noisy test job before it fills the disk.
- Read and write the five crontab time fields, including ranges, lists and steps
- Add, list and remove jobs with crontab, and send their output to a log file
- Debug a failing cron job: minimal PATH, missing output and /etc/cron.d format
- Find the scheduled jobs of other users and of the system
cron is the Linux scheduler. A background service (the cron daemon) wakes up every minute, checks every schedule it knows, and runs the commands that are due.
Every schedule is one line with five time fields and a command:
┌───────── minute (0 - 59)
│ ┌─────── hour (0 - 23)
│ │ ┌───── day of month (1 - 31)
│ │ │ ┌─── month (1 - 12)
│ │ │ │ ┌─ day of week (0 - 7, 0 and 7 are Sunday)
│ │ │ │ │
* * * * * command to run| Symbol | Meaning | Example | Reads as |
|---|---|---|---|
* | every value | * * * * * | every minute |
, | a list | 0 9,18 * * * | at 09:00 and 18:00 |
- | a range | 0 9 * * 1-5 | 09:00 Monday to Friday |
/ | a step | */10 * * * * | every 10 minutes |
Schedules live in three places: each user's crontab (edited with crontab -e), files in /etc/cron.d/ for system jobs, and the folders /etc/cron.daily/, cron.hourly, cron.weekly for scripts that just need to run "about once a day".
On modern servers systemd timers do the same job and are worth knowing too, but cron is everywhere and comes up in almost every Linux interview.
- Press Start lab. You get your own Ubuntu machine on the right, just for you.
- Read each step. Commands with a ▶ Run button can be sent to the terminal in one click, but typing them yourself helps you remember.
- Do the Your task part, then press Check my work. The check looks at the machine and tells you what is right or still missing.
- Stuck? Open the hint. Nothing you do here can break anything real.
Your first cron job
Schedule a heartbeat that writes the time to a log every minute, and watch cron run it.
Why we do this: a "heartbeat" job is the simplest way to prove that cron is running and that your schedule is right before you trust it with something important like backups.
1. Is cron running?
pgrep -a cronOn a full server you would check with systemctl status cron (it is called crond on Red Hat based systems).
2. List your crontab
crontab -l"no crontab for root" means you have no jobs yet.
3. Add a job
crontab -eThe first time, it asks which editor to use: pick nano (usually 1). Add this line at the bottom, then save with Ctrl+O, Enter and exit with Ctrl+X:
* * * * * date >> /var/log/heartbeat.logYou should see crontab: installing new crontab. That means cron checked your line and accepted it. A typo in the time fields is rejected right here.
Never run
crontab -rby accident. It deletes your whole crontab without asking, and-rsits right next to-eon the keyboard.
4. Watch it run
crontab -l
tail -f /var/log/heartbeat.logWithin a minute or two the first line appears (cron picks up a changed crontab on its next check, then runs the job at the start of a minute), and then a new line arrives every minute. Press Ctrl+C to stop watching. Cron always runs jobs at the start of a minute (second :00).
Add a job to root's crontab that appends the output of date to /var/log/heartbeat.log every minute, and wait until cron has run it at least once.
Expected result: crontab -l shows the job, and /var/log/heartbeat.log has at least one line written by cron.
Hint: the commands, explained
Without opening an editor, you can also install it with:
(crontab -l 2>/dev/null; echo '* * * * * date >> /var/log/heartbeat.log') | crontab -Then wait a minute or two: tail -f /var/log/heartbeat.log
What each part does
crontab -l 2>/dev/null: print your current cron jobs (and hide the error if you have none yet).echo '* * * * * date >> /var/log/heartbeat.log': the new job: five*= every minute; the command appends the date to a log.( ... ; ... )runs both and joins their output;| crontab -installs that combined list as your new crontab. This adds a job without deleting the old ones.
Real schedules
Run the backup every night at 02:30 and the temp clean-up every 15 minutes on weekdays.
Why we do this: real jobs run at quiet times (backups at night), at a steady rhythm (clean-ups every few minutes) or only on working days. Getting a field wrong means a backup that never runs, or one that runs every minute all night.
1. Practise reading schedules
| Schedule | Meaning |
|---|---|
30 2 * * * | every day at 02:30 |
0 */6 * * * | every 6 hours, on the hour |
*/15 * * * 1-5 | every 15 minutes, Monday to Friday |
0 9 1 * * | 09:00 on the 1st of every month |
0 0 * * 0 | midnight every Sunday |
There are also shortcuts: @reboot (once at start-up), @hourly, @daily, @weekly, @monthly.
Cron uses the server's time zone. Check it with date or timedatectl. Most servers run in UTC, so "02:30" might not be 02:30 where you live.
2. Always capture the output
By default cron tries to email a job's output to the user, which on most servers goes nowhere. So we redirect it to a log file:
30 2 * * * /usr/local/bin/backup-shop.sh >> /var/log/backup-shop.log 2>&1>> appends normal output, and 2>&1 sends errors to the same place. Without it, a failing job leaves no trace at all.
3. Use full paths
The scripts for this step are ready in /usr/local/bin:
cat /usr/local/bin/backup-shop.sh /usr/local/bin/cleanup-tmp.shIn cron, always write the full path to scripts and files. You will see why in the next step.
Add two jobs to root's crontab (keep the heartbeat for now):
/usr/local/bin/backup-shop.shevery day at 02:30, appending all output to/var/log/backup-shop.log./usr/local/bin/cleanup-tmp.shevery 15 minutes, Monday to Friday only.
Expected result: crontab -l shows three jobs: heartbeat, backup and clean-up.
Hint: the commands, explained
30 2 * * * /usr/local/bin/backup-shop.sh >> /var/log/backup-shop.log 2>&1
*/15 * * * 1-5 /usr/local/bin/cleanup-tmp.sh >> /var/log/cleanup-tmp.log 2>&1What each part does
- These are crontab lines: add them with
crontab -e(it opens an editor). 30 2 * * *= minute 30, hour 2, every day: 02:30 every night.*/15 * * * 1-5= every 15 minutes, Monday (1) to Friday (5).>> FILE 2>&1: append both normal output and errors to a log file, because cron has no screen to show them on.
Debug a job that never works
Fix the system cron job so the shop report is actually generated.
Why we do this: "the script works when I run it, but not from cron" is the most common cron problem of all. The cause is almost always the environment: cron runs jobs with a tiny PATH and none of your shell settings.
1. Look at the system job
cat /etc/cron.d/shop-reportFiles in /etc/cron.d/ have one extra field compared with a user crontab: the user to run as (root here), between the schedule and the command.
2. It works by hand...
report-gen
which report-gen3. ...but not from cron
cat /var/log/shop-report.logreport-gen: command not found. Your interactive shell has /opt/tools/bin in its PATH (it was added in .bashrc), but cron never reads .bashrc. Cron's PATH is only /usr/bin:/bin.
You can see what a job really gets by scheduling env > /tmp/cron-env.txt and comparing it with env in your terminal.
4. Two ways to fix it
Use the full path in the command:
* * * * * root /opt/tools/bin/report-gen > /var/log/shop-report.log 2>&1Or set PATH at the top of the file:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/tools/bin
* * * * * root report-gen > /var/log/shop-report.log 2>&1Edit the file with nano /etc/cron.d/shop-report. Cron notices the change by itself, no restart needed.
Other classic gotchas
%has a special meaning in crontab lines (it means "new line"). Writedate +\%F, or move the command into a script.- Files in
/etc/cron.d/must be owned by root, not writable by others, and their names may not contain dots. - On a real server, cron logs each run:
grep CRON /var/log/syslog(Ubuntu) orjournalctl -u cron.
Fix /etc/cron.d/shop-report so that cron can run report-gen, then wait a minute or two.
Expected result: cat /var/log/shop-report.log shows a line containing "report generated".
Hint: the commands, explained
sed -i 's# report-gen# /opt/tools/bin/report-gen#' /etc/cron.d/shop-report
cat /etc/cron.d/shop-reportThen wait up to a minute and check the log again.
What each part does
sed -i 's#OLD#NEW#' FILE: edit the file in place, replacing the first match on each line.#is used as the separator instead of/because the replacement contains slashes.- This changes the job from
report-gen(which cron can't find, because cron's PATH is minimal) to the full path/opt/tools/bin/report-gen. catprints the file so you can confirm the change.
Audit and clean up
Remove the heartbeat job without touching the others, and find what the deploy user runs.
Why we do this: a forgotten every-minute test job can fill a disk or hammer an API for months. And when you take over a server, one of the first questions is "what runs on a schedule here?", because jobs hide in several places and under several users.
1. Remove one job, keep the rest
crontab -eDelete the heartbeat line (in nano, put the cursor on it and press Ctrl+K), save and exit. Check:
crontab -lTo pause a job instead of deleting it, put # at the start of its line.
Before big crontab edits, keep a copy:
crontab -l > ~/crontab.backup. You can restore it withcrontab ~/crontab.backup.
2. Other users' jobs
As root you can read and edit anyone's crontab:
crontab -u deploy -l
ls -l /var/spool/cron/crontabs/Each user's crontab is stored as a file in /var/spool/cron/crontabs/, but always use crontab -u USER -e to change it rather than editing the file directly.
3. System-wide jobs
cat /etc/crontab
ls /etc/cron.d/ /etc/cron.daily/ /etc/cron.hourly//etc/cron.daily/ contains ordinary scripts (no schedule lines), for example logrotate. On a systemd server, also run systemctl list-timers.
A quick audit of every user's crontab:
for u in $(cut -d: -f1 /etc/passwd); do crontab -u "$u" -l 2>/dev/null | grep -v '^#' | sed "s/^/$u: /"; done- Remove the heartbeat job from root's crontab, keeping the backup and clean-up jobs.
- Find the script the deploy user runs on a schedule and write its full path into
/root/deploy-job.txt.
Expected result: crontab -l shows only the backup and clean-up jobs, and /root/deploy-job.txt holds one path.
Hint: the commands, explained
crontab -l | grep -v heartbeat | crontab -
crontab -u deploy -l
echo /path/to/the/script > /root/deploy-job.txtWhat each part does
crontab -l | grep -v heartbeat | crontab -: print your jobs, drop every line containingheartbeat(-v= invert), and install what's left.crontab -u deploy -l: as root, list the cron jobs of userdeploy.- Read the script path from that output and save it with
echo PATH > /root/deploy-job.txt.
Brilliant work!
You put the shop's routine work on a schedule, fixed the classic "works by hand, fails in cron" bug and audited every scheduled job on the machine.
Interview-ready takeaways:
- Five fields: minute, hour, day of month, month, day of week.
*/15is a step,1-5a range,9,18a list.@rebootand@dailyare shortcuts. crontab -eedits,crontab -llists,crontab -u USER -lreads another user's jobs.crontab -rdeletes everything without asking.- Cron runs with a minimal
PATHand no.bashrc: use full paths, setPATH=in the crontab, and always redirect output with>> file 2>&1. /etc/cron.d/files have an extra user field. Times follow the server's time zone. Escape%as\%.- To audit a server, check user crontabs,
/etc/crontab,/etc/cron.d/, thecron.daily-style folders andsystemctl list-timers.
Next: the Environment Variables & Shell Config lab.
Read and write crontab schedules, run a backup every night, debug a cron job that works by hand but fails on schedule, and clean up jobs safely.
The shop's backups and reports still depend on someone remembering to run them. You will put them on a schedule with cron, fix the nightly report that "works when I run it" but never produces anything on schedule, and remove a noisy test job before it fills the disk.