Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Part 2 · System administration · Lesson 12 · 30 minutes

Run a script on a schedule

After this lesson you can
  • Write a cron line for a given time and install it without losing your other jobs
  • Say when to use at and when to use a systemd timer
  • Check a timer schedule with systemd-analyze before you use it
Lab files of this lesson (24)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

The log checker of lesson 11 works when you start it. Your lead wants it to run by itself at 06:30 every morning, and a second script every quarter of an hour. Nobody will watch the terminal, so a job must use full paths and keep its output in a file. You test a job that runs every minute, write the real lines, and learn two other ways to start a job later.

Recall

What do the exit codes 0, 1 and 2 of check-log.sh mean?

0 is clean, 1 is "found something" or "cannot read the log", and 2 is a wrong call (lesson 11). A scheduler does not read the code by itself: the job must write its result to a log.

Which key of a unit file holds the command that systemd starts?

ExecStart=, with the full path of the program. When it is wrong, systemctl status shows status=203/EXEC (lesson 8).

The idea

cron is a service that runs a command at set times. Each job is one line: five time fields, then the command. crontab is the program that manages your list of jobs.

FieldValues
minute0 to 59
hour0 to 23
day of month1 to 31
month1 to 12
day of week0 to 7 (0 and 7 are Sunday), or mon to sun

In a field, * means "every", 1-5 is a range, */15 is "every 15", and , makes a list. A job has a small environment and no terminal. So use full paths, and send the output to a file with >> and 2>&1.

Two other tools start a job. at runs it once, at a time that you name. A systemd timer is a .timer unit that starts a .service unit of the same name, and the output goes to the journal. Cron is the shortest for a repeated job, at is for a single run, and a timer is for a job that needs the journal, a dependency or a catch-up after a shutdown.

The checker of lesson 11 would run from a line with these parts:

The cron line, taken apart
30minute6hour*day of month*month*day of weekcmdthe program to run30minute6hour*day of month*month*day of weekcmdthe program to run

Worked example

1. Install a test job that runs every minute

crontab -l shows your list, crontab FILE installs a list of jobs from a file, crontab -e edits it in your editor, and crontab -r removes it with no question. crontab FILE replaces every job that you have. So the test below saves your list first and puts it back at the end. Work in the folder of lesson 11. The script stamp.sh prints the time.

mkdir -p ~/krlab/linux-admin/sh && cd ~/krlab/linux-admin/sh

sh/stamp.sh

#!/usr/bin/env bash
echo "stamp $(date +%H:%M)"
chmod +x stamp.sh
crontab -l > crontab.backup 2>/dev/null
echo "* * * * * $PWD/stamp.sh >> $PWD/stamp.log 2>&1" > mycron.txt
crontab mycron.txt
crontab -l
sleep 75
cat stamp.log
wc -l < stamp.log
crontab crontab.backup
* * * * * /home/you/krlab/linux-admin/sh/stamp.sh >> /home/you/krlab/linux-admin/sh/stamp.log 2>&1
stamp 12:22
1

The first command saves your list in crontab.backup (empty if you had no jobs), and the last command puts it back. The job ran once or twice in the 75 seconds, and wc -l counts the lines of the log.

2. Write the line for the checker

The real line runs the checker of lesson 11 on the login log, and keeps the report:

30 6 * * * /home/you/krlab/linux-admin/sh/check-log.sh /var/log/auth.log >> /home/you/krlab/linux-admin/sh/report.txt 2>&1

It runs at 06:30 every day. On Ubuntu only the group adm may read /var/log/auth.log, and the first account of the system is a member. If id does not list adm for your account, the report will say cannot read: /var/log/auth.log every morning. The checker exits with 1 when it finds an address, and cron does nothing with that code, so the line of ALERT in report.txt is the signal. System-wide jobs go into files in /etc/cron.d/, which have an extra field for the user.

3. Run a job once with at

at takes the commands from its input and runs them once. atq lists the waiting jobs, atrm NUMBER removes one, and the package is called at. A job that at has run is gone from the list.

echo "$PWD/stamp.sh >> $PWD/stamp.log" | at now + 1 minute
atq
sleep 70
tail -n 1 stamp.log

at prints a job number and the time, and atq shows the same job. After 70 seconds stamp.log has a new line. This step was not run for this lesson, because the test machine has no at.

4. Read a timer schedule before you use it

A timer says when it runs with OnCalendar=. The words are not the five fields of cron, and a wrong value is a silent mistake. systemd-analyze calendar reads a value and prints the form that systemd understood. It needs no root and starts nothing.

systemd-analyze calendar "*-*-* 06:30:00" "minutely" "Mon..Fri 06:30" | grep -E "Original|Normalized"
Normalized form: *-*-* 06:30:00
  Original form: minutely
Normalized form: *-*-* *:*:00
  Original form: Mon..Fri 06:30
Normalized form: Mon..Fri *-*-* 06:30:00

The normal form is weekday year-month-day hour:minute:second. *-*-* 06:30:00 is every day at 06:30, and minutely means second 00 of every minute. When a value is already in normal form, the tool leaves out the line "Original form". The command also prints the next time that the value matches. systemd-analyze calendar --iterations=5 VALUE shows the next five.

The real timer for a job needs two unit files. Persistent=true runs a job that was missed while the machine was off, and systemctl list-timers shows the next and the last run of every timer.

How a timer runs a job
Clockkr-stamp.timerkr-stamp.serviceJournalthe time matches OnCalendarthe timer starts the servicethe output of date is storedClockkr-stamp.timerkr-stamp.serviceJournal123
  1. Clock → kr-stamp.timer: the time matches OnCalendar
  2. kr-stamp.timer → kr-stamp.service: the timer starts the service
  3. kr-stamp.service → Journal: the output of date is stored
Optional: the timer files kr-stamp.timer and kr-stamp.service (a tested pair)

sh/kr-stamp.timer

[Unit]
Description=Run the stamp service every minute

[Timer]
OnCalendar=minutely
Persistent=true

[Install]
WantedBy=timers.target

sh/kr-stamp.service

[Unit]
Description=Print a time stamp

[Service]
Type=oneshot
ExecStart=/usr/bin/date

Both files belong in /etc/systemd/system/ (install them as in lesson 8). After sudo systemctl enable --now kr-stamp.timer, the next run is less than a minute away, and the journal of the service holds the output of date. Remove them with sudo systemctl disable --now kr-stamp.timer and sudo rm of the two files.

Your turn

Your lead gives you three jobs. Write them as three lines in a file jobs.txt in the folder ~/krlab/linux-admin/sh, with these schedules and these programs:

  1. /srv/data/bigfiles.sh /srv/data 5000 (lesson 11), at 06:30 from Monday to Friday only.
  2. /usr/local/bin/tidy.sh, every 15 minutes, all day.
  3. /opt/report.sh, at 02:15 on the first day of every month.

There are no steps here. Use the table of fields. Give each job a log file with >> and 2>&1.

Last, install jobs.txt with the save-and-restore commands of step 1, check that crontab -l shows three lines, and put your old list back. The jobs name programs that do not exist on your machine. They never run, because you restore your list at once.

Check yourself

A cron job works when you run it by hand, but fails from cron. Name two likely causes.

The environment: cron gives a short PATH and no terminal, so a program found by name may be missing, and a relative path points to another folder. Use full paths. Also the output: without a redirect it is mailed or lost. Write >> log 2>&1.

You run "crontab newjobs.txt" and your old jobs are gone. Why, and how do you avoid it?

crontab FILE replaces the whole list. Save the old list first with crontab -l > crontab.backup, put the old and the new lines in one file, or edit the list with crontab -e.

When do you use at, and when a systemd timer, and not cron?

Use at for a job that runs once. Use a timer when you want the log in the journal, a dependency on other units, a missed run to be made up (Persistent=true), or resource limits. Cron is shorter for a single repeated job.

Field notes

  • Cron is also a way for an attacker to stay on a machine (MITRE ATT&CK, "Scheduled Task/Job", T1053). Look at crontab -l of every user, /etc/cron.d/ and systemctl list-timers when you audit a system.
  • In a crontab line, a % means a line break. Write \% where you need the sign, for example in date +\%H:\%M, or put the command in a script, as this lesson does with stamp.sh.
  • A job that is not watched needs a log that someone reads. Write the result to a file, as the checker does, and look at the file after the first night.
  • Test a timer value with systemd-analyze calendar before you install the unit. A value that never matches gives no error message at run time.