Chapter 4: Linux Advanced Commands
4.9 Scheduling tasks: cron
In short: cron runs commands automatically on a schedule.
cron runs commands automatically on a schedule. Edit your table with crontab -e, list with crontab -l.
┌──────── minute (0-59)
│ ┌────── hour (0-23)
│ │ ┌──── day of month (1-31)
│ │ │ ┌── month (1-12)
│ │ │ │ ┌ day of week (0-6, with 7 also Sunday in Cronie)
│ │ │ │ │
* * * * * command
| Schedule | Meaning |
|---|---|
*/5 * * * * |
Every 5 minutes |
0 2 * * * |
Every day at 02:00 |
30 9 * * 1-5 |
09:30 Monday to Friday |
0 0 1 * * |
Midnight on the 1st of every month |
@reboot |
On cron daemon startup where supported |
The workshop wants an inspection report at 01:30 each day in the intended scheduler timezone. Read the following row as an example before preparing your own entry in the lab.
Workshop चा inspection report रोज scheduler च्या timezone मध्ये 01:30 ला तयार व्हावा ही गरज आहे. ही ओळ उदाहरण म्हणून वाचा आणि खालील lab मध्ये स्वतःची entry तयार करा.
Workshop को रोज़ scheduler के timezone में 01:30 पर inspection report चाहिए। इस पंक्ति को उदाहरण के तौर पर पढ़ें और नीचे के lab में अपनी entry तैयार करें।
# Illustrative only. The paths below are placeholders.
30 1 * * * /bin/sh /path/to/report.sh /path/to/inspection-data
Cronie parses an unescaped % in the command portion before the shell runs. Keep date formatting in the report script to avoid that table syntax in the entry.
cron on Amazon Linux 2023
Amazon Linux 2023 does not include Cronie by default. AWS documents systemd timers as its recommended alternative. Use a prepared cron lab or the offline rehearsal below. Verify the scheduler’s applicable timezone rather than changing the host clock settings.
Ravindra Bagale's Tip
Rehearse the job under its intended account with the interpreter, paths and environment it will have when scheduled. Verify the result and captured diagnostics.
Ravindra Bagale's Tip – मराठी
Job schedule करण्यापूर्वी योग्य account, interpreter, paths आणि environment वापरून चालवा. Report आणि diagnostics तपासा.
Ravindra Bagale's Tip – हिंदी
Job schedule करने से पहले उसे सही account, interpreter, paths और environment के साथ चलाएँ। Report और diagnostics जाँचें।
Ravindra Bagale's Tip
Check which scheduler is installed and which timezone the schedule uses. The offline lab runs the command without editing system configuration or needing a cron daemon.
Ravindra Bagale's Tip – मराठी
कोणता scheduler install आहे आणि schedule कोणत्या timezone मध्ये आहे हे तपासा. Offline lab साठी system configuration बदलण्याची किंवा cron daemon चालू असण्याची गरज नाही.
Ravindra Bagale's Tip – हिंदी
कौन-सा scheduler install है और schedule किस timezone में है, यह जाँचें। Offline lab के लिए system configuration बदलने या cron daemon चलाने की जरूरत नहीं है।
Lab
खालील workshop lab मध्ये आधी report हाताने चालवा, दोन failures मोजले आहेत का ते तपासा आणि schedule entry चा preview पहा. तयार केलेल्या lab account मध्ये वेळेवर चालवण्याची चाचणी केली तर शेवटी फक्त ही entry काढा.
Got it? Five fields – minute, hour, day, month, weekday – and full paths. Now let's move on to environment variables.
समजलं का? पाच फील्ड्स – minute, hour, day, month, weekday – आणि फुल पाथ्स. आता पुढे जाऊया environment variables कडे.
समझ आया? पाँच फ़ील्ड्स – minute, hour, day, month, weekday – और फ़ुल पाथ्स. अब आगे चलते हैं environment variables की तरफ़.
Choose what should happen between shifts
The Mauli workshop wants an inspection summary waiting for the opening shift every morning. The input file already lives on the Linux machine. A command can count the failed rows whenever a person runs it. On a good day someone remembers to do that before leaving. The scheduling problem is to arrange for a known account to run the same checked command at a known time, capture the result, and make any failure visible. A scheduler is useful when the work should happen independently of a person's terminal session.
Cron is a traditional scheduler for Unix-like systems. A daemon is the background service that examines schedules and starts matching commands. A crontab is the input table describing those jobs for the scheduler. The crontab program can display or edit a user's table. Installing a table says what the daemon should attempt, and successful execution depends on the daemon being available and on the job's own environment and inputs. Separate those concerns before debugging a missed report.
A user crontab belongs to a particular account and its commands run with that account's privileges. Use crontab -l to display your current table and crontab -e to edit it with the configured editor. When first learning, do the offline exercise to prepare and test the entry before installing anything. If your prepared training Linux has a working cron daemon and you have an allowed lab account, the later optional step shows how to add and remove just one identified entry. The lesson does not require installing a new service, changing the machine clock, or scheduling a real production backup.
System tables are a separate arrangement. On implementations such as Cronie, a job in /etc/crontab or an applicable file under /etc/cron.d includes a username after the five time fields. A personal crontab entry has no username in that position. If you place an example username there in your own table, cron can pass it to the shell as the first word of the command. The shell then attempts to run a program with that name. Identifying the format of the table is an ordinary prerequisite before copying any example.
Read the five fields as a calendar filter
A conventional job line in a user crontab starts with five whitespace-separated fields. They describe minute, hour, day of month, month, and day of week, in that order. The remaining text is the command. The scheduler checks the current calendar time against the fields. An asterisk usually means all possible values in its position. The first asterisk does not mean “every” in any unit other than minutes. The same character in the month position permits any month. Count positions before reading the command, because shifting one numeric value left changes the schedule.
| Position | Field | Common values | Example |
|---|---|---|---|
| 1 | Minute | 0 through 59 | 30 means half past the hour |
| 2 | Hour | 0 through 23 | 1 means the hour after midnight |
| 3 | Day of month | 1 through 31 | 1 means the first day |
| 4 | Month | 1 through 12 | 11 means November |
| 5 | Day of week | 0 through 6 in standard numeric usage, with 7 also Sunday in Cronie | 1-5 means Monday through Friday |
Start with 30 1 * * *. The minute is 30, hour is one, and the remaining fields impose no calendar restriction. It describes 01:30 daily in the scheduler's applicable timezone. 30 9 * * 1-5 describes 09:30 on weekdays. A comma list is another way to name field values. For example, 0,30 8-10 * * * allows minutes zero and 30 in each of the three selected hours. Write out the six candidates: 08:00, 08:30, 09:00, 09:30, 10:00, and 10:30. This interpretation uses the two fields together instead of imagining that one value starts a repeating stopwatch.
On Cronie and other implementations with step syntax, */15 * * * * chooses minutes zero, fifteen, thirty, and forty-five within each hour. The range starts over in the next hour. */35 in the minute field would select zero and thirty-five, leaving a 25-minute gap between minute 35 and the next hour. This difference matters if the workshop asks for elapsed intervals rather than repeating calendar moments. A schedule written down and manually expanded is easier to review than a verbal assertion that something runs “every so often.”
Take care when setting both day fields. In Cronie, if both day of month and day of week are restricted, either matching day can qualify, provided the other time fields match. 0 8 1 * 1 can start a job at 08:00 on the first day of a month and on every Monday. It does not express only the first Monday. To express that narrower requirement, one practical design is to schedule Mondays and have the job explicitly require the day of month to be one through seven in the chosen timezone. If a date matches both day conditions, that single cron entry qualifies once for that minute. Study your implementation's rule before relying on mixed day restrictions.
Calendar values also meet real calendars. 0 8 31 * * has no run on the 31st in a month without that day. Where supported, job shortcuts such as @reboot are separate syntax, generally starting a job when the cron daemon starts under its implementation's rules. A daemon startup does not ensure that every dependent service or network share is ready. For startup or missed-run requirements check the actual scheduler's behavior on that host rather than inferring it from the shortcut name.
State which clock the schedule follows
Imagine that the workshop expects the nightly report at 01:30 India Standard Time and the scheduler matches time in UTC. With a five-hour-thirty-minute offset, that instant is 20:00 on the previous UTC calendar day. On paper a UTC daily table would use 0 20 * * * for that requirement. If the report instead needs to run Monday through Friday at that local time, the equivalent UTC weekdays are Sunday through Thursday. Converting the hour without moving the date would choose the wrong set of active days. Record the intended timezone and the matching calendar fields together.
Cronie supports a CRON_TZ setting to choose the timezone used for schedule matching in the table. Other implementations differ. Read the local manual before using it. The daemon's timestamp on a journal entry and the program's own report timestamp can still follow different settings. A job that needs data for a specific local calendar day should use an explicit, documented timezone for its own computation. Where possible, record both the intended local schedule and an unambiguous timestamp including the offset or UTC marker. This makes correlation possible when the machine and the report reader use different clocks.
Zones with seasonal clock changes can repeat or skip wall-clock times. Scheduler implementations and job patterns can have special handling for those transitions. Cronie's daemon documentation, for example, describes special treatment of certain fixed-time jobs during small clock changes. Rather than promising a universal result on a transition day, test the chosen implementation or pick a schedule with documented handling. If a report must catch up after the machine was off, consider a scheduler with that explicit feature. The ordinary recurring calendar line on its own is not a promise to replay every missed run.
Take a worked calendar example using July 2026. The first day of that month is a Wednesday and its first Monday is July 6. A scheduler reading 0 8 1 * 1 in Cronie can dispatch on July 1, 6, 13, 20, and 27 at the applicable 08:00 time. A first-Monday rule designed by scheduling Mondays and checking that the date falls from one through seven accepts July 6 alone. In a month whose first day is already Monday, the broad condition still produces only one invocation for that particular minute. Writing the expected date list catches the ambiguous interpretation before a two-minute demo is mistaken for long-term validation.
The reporting date can require a separate decision from the trigger date. The job that starts at 01:30 Tuesday in India might summarize all inspections recorded on Monday local time. Its UTC log timestamp belongs to Monday at 20:00, and that timestamp by itself does not identify the report's intended business day. A correct data selection would define the start and end of Monday in the chosen zone and store that date with the report. If a delayed execution occurs later on Tuesday, it should still be clear which input period to process. That clarity also helps a manual rerun work on the same record set.
For a schedule handed to another operator, document a literal example instant, the relevant input period, and the observation that will count as successful completion. In the simple lab input all four lines are always included, so the count does not depend on calendar conversion. In a real scheduled task, a successful process could still choose the wrong day's rows. Compare a representative record just before midnight and one just after it to confirm the period boundaries. The scheduler is responsible for launching a command at an eligible time, while the program is responsible for selecting the data it names in the output.
Prepare a command that works away from your terminal
Most schedule problems students see after an apparently good manual run involve a difference in context. An interactive shell may load a startup file that extends its search path, sets variables, or defines shortcuts. A scheduled command runs without your current prompt, aliases, shell state, and current directory assumptions. Cronie typically passes its command to /bin/sh unless the table sets a different SHELL. It constructs some values such as HOME and LOGNAME for the owner. The precise environment depends on the daemon and your system. Make the job's small set of needs explicit so you can reproduce it independently.
A program's PATH is the list of directories it searches for a command such as awk when you use the bare name. The installed job and its data directory can instead be named by explicit paths. The shell that launches the job might have a different working directory, so construct data paths from a known directory instead of assuming it begins beside the script. Shell variables from your terminal are not job inputs unless the scheduled process actually receives them. This lab uses a script file and one ordinary argument naming its scratch directory.
Use Bash for the setup commands and the same terminal through cleanup. The script executed by the scheduler is intentionally ordinary sh. The scratch name is created below the system's temporary directory with a controlled template containing no spaces or percent signs. The quoted shell paths still keep the boundaries clear. This exercise writes only a few lines of fictional data, requires no AWS credentials or network access, and can be completed without cron installed.
cron_lab=$(mktemp -d /tmp/mauli-cron.XXXXXXXX) || exit 1
printf 'Lab directory: %s\n' "$cron_lab"
cat > "$cron_lab/runs.txt" <<'RUNS'
press-a passed
press-b failed
press-c passed
press-a failed
RUNS
cat > "$cron_lab/report.sh" <<'SCRIPT'
#!/bin/sh
set -eu
PATH=/usr/bin:/bin
export PATH
workdir=${1:?missing training directory argument}
input="$workdir/runs.txt"
if [ ! -r "$input" ]; then
printf 'Cannot read the inspection input: %s\n' "$input" >&2
exit 2
fi
count=$(awk '$2 == "failed" { failures++ } END { print failures+0 }' "$input")
timestamp=$(date -u '+%Y-%m-%dT%H:%M:%SZ')
printf '%s workshop-report failures=%s\n' "$timestamp" "$count"
SCRIPT
/bin/sh -n "$cron_lab/report.sh"
The script reads four known records and counts two failures. It deliberately reports a timestamp in UTC, with a final Z marking that timezone. set -e helps stop this simple script if a command fails before the final print, and set -u protects against reading a missing variable. The argument expansion names the problem if the job receives no directory. The explicit readable-file test produces a diagnostic for this fixture's known missing-input case. For a real reporting tool also validate the input format and distinguish an intentionally empty dataset from missing or incomplete records.
The /bin/sh -n command checks shell syntax without executing the report. Passing the syntax check is a first step. The script could still fail to find its input at runtime, or its arithmetic could answer the wrong question. Those require execution checks with known values. We call the script with /bin/sh, so it does not need an executable bit for this exercise. In a published job decide how the script should be invoked, then use the same interpreter and permissions in tests.
env -i PATH=/usr/bin:/bin "HOME=$cron_lab" /bin/sh "$cron_lab/report.sh" "$cron_lab" \
> "$cron_lab/manual.log" 2>&1
printf 'manual status=%s\n' "$?"
cat "$cron_lab/manual.log"
manual status=0
2026-07-01T20:00:00Z workshop-report failures=2
The displayed timestamp is an illustrative value. Your actual clock supplies the date and time. env -i starts this test with an empty inherited environment, then adds the two settings shown. This is a rehearsal of a minimal environment, not a claim to reproduce every variable or security context the cron daemon can set. It helps expose a script that needs a setting silently inherited from your terminal. The redirection captures both result and diagnostics in a new file you own. The two expected facts are status zero and a line ending in workshop-report failures=2.
Intentionally move the known input aside to test the failing path, then return it to its original name. The check uses a separate output file, so there is no confusion about which run produced which result. When writing a real job, validate failures separately from successes. A report that always prints zero failures after an unavailable source can hide a very different problem from a clean inspection.
mv "$cron_lab/runs.txt" "$cron_lab/runs.saved.txt"
env -i PATH=/usr/bin:/bin "HOME=$cron_lab" /bin/sh "$cron_lab/report.sh" "$cron_lab" \
> "$cron_lab/missing.log" 2>&1
printf 'missing-input status=%s\n' "$?"
cat "$cron_lab/missing.log"
mv "$cron_lab/runs.saved.txt" "$cron_lab/runs.txt"
missing-input status=2
Cannot read the inspection input: /tmp/mauli-cron.EXAMPLE/runs.txt
Use an ordinary interactive Bash for the lab; a shell configured to exit immediately on failures can skip the print or the restoration in this demonstration. In that case run the expected failure as the condition of an if and capture its status in the failure branch. The successful and missing cases now show two visibly different outcomes. Keep that distinction in the scheduled version's log handling too.
Preview a complete schedule entry
Write a short table fragment containing one proposed job. The first line is a comment identifying this lab and the generated path. The following line uses one asterisk in each position for a temporary training run once per matching minute. Keep the comment on its own line. Characters after the five fields are part of the command, so an inline comment is not a general crontab comment. The following script prints the text and saves it for review. It does not install that text as a schedule.
{
printf '# Mauli cron exercise %s\n' "$cron_lab"
printf '* * * * * /bin/sh "%s/report.sh" "%s" >> "%s/cron.log" 2>&1\n' \
"$cron_lab" "$cron_lab" "$cron_lab"
} > "$cron_lab/entry.preview"
cat "$cron_lab/entry.preview"
# Mauli cron exercise /tmp/mauli-cron.EXAMPLE
* * * * * /bin/sh "/tmp/mauli-cron.EXAMPLE/report.sh" "/tmp/mauli-cron.EXAMPLE" >> "/tmp/mauli-cron.EXAMPLE/cron.log" 2>&1
Each instance of EXAMPLE is replaced by the generated suffix from your own terminal. The pathname is literal in the table, so the cron process does not need the cron_lab variable. The shell running the job expands only what belongs to the command portion. The >> redirect appends output, preserving observations from distinct invocations. The 2>&1 copy then sends diagnostics to that same current output destination. If the account cannot open the log for append, the shell can fail before the script starts. Ensure the directory remains writable by the intended account until you remove the lab entry.
Cronie treats an unescaped percent sign in the command specially: the first such sign ends the shell command and subsequent data becomes its input, with unescaped percent signs used as line breaks. The cron parser reads this character before the command reaches the shell, so shell quoting alone does not necessarily protect it. Our schedule line contains no percent signs. The date formatting with percent signs lives inside the external script and is interpreted by date during the actual run. Keeping a nontrivial command in a script makes the schedule easier to review and reduces interactions between two parsers.
If you are using a Cronie build that implements the documented -T option, check the isolated preview with crontab -T "$cron_lab/entry.preview". This verifies table syntax without installing it. A successful check does not run the shell command or prove that the account can access the files. Use the manual execution results to verify that part. On another implementation, use its own syntax-checking mechanism if available. Calling crontab with a file argument and no check option generally installs or replaces the current table. It is not a syntax-only preview.
Inspect the format of the final line. There must be five schedule fields, followed immediately by the command, with no username column in your personal table. The file should end in a newline. If a program copy introduces Windows line endings, the end of the command can contain an unexpected carriage return. The preview uses printf to write the line with an ordinary Unix newline. If you parse a file generated elsewhere, inspect the actual text before diagnosing a scheduling mystery.
Observe a real schedule only in a prepared lab account
The offline checks can be completed on any compatible terminal. To observe actual daemon timing, use a Linux practice account prepared with cron, where you are allowed to add a job and no shared service depends on your scratch data. First identify the account with id -un, check that the crontab command is present, and read the existing table with crontab -l. Some installations report that there is no table yet. If there is an existing table, preserve its contents and review any environment assignments that could affect the new row. Keep a separate copy of the original as part of the lab record, without exporting unrelated secrets.
Use crontab -e to append just the two lines displayed from your own preview. Save and close the editor, then use crontab -l again to verify that both lines were added exactly once. Do not install the preview file as the entire table. An install of a whole file can replace jobs you did not mean to change. Contact with the cron command and a currently running daemon are different prerequisites. If the implementation is present but inactive on a lab machine, use the offline result or have the lab owner investigate its setup. A job in your table is not an instruction to start or reconfigure a system service.
Observe a few matching minute boundaries and read cron.log under the recorded scratch path. If the daemon is running and has read the new entry, the expected evidence is a timestamped line for each successful execution, each with two failures as the computed fixture result. Compare the timestamps with the schedule and allow for when the table was loaded and the job was dispatched. A missing file can indicate that the job has not attempted to run, or that the shell could not open the output path. If the file exists and holds the missing-input diagnostic, the daemon may have launched the job successfully while the application failed. Trace evidence from scheduler to shell to script.
After observing the run, remove the exact job and its preceding comment in the same editor, and confirm both are absent with crontab -l. Preserve any unrelated entries. Deleting the file or logging out of the terminal does not remove a scheduled job. Removing the entry does not necessarily stop a process it already started. For the simple report, allow the short job to finish before deleting the scratch path. Do not use crontab -r as a one-job cleanup command. It removes an entire user's table on common implementations.
Without a runnable daemon on your machine, record the verified manual, missing-input, and entry-preview observations. Those are enough to explain the expected dispatch and job outcome as distinct events. On Amazon Linux 2023, AWS documents that Cronie is not installed by default and recommends systemd timers. An administrator can choose the supported scheduler for their image and workload. Installing a package or changing the host timezone is unnecessary to learn these mechanics. A systemd timer consists of a timer unit and a unit to activate, so it uses a different configuration format from a cron row.
Decide what should happen when two runs would overlap
The workshop's training report runs too quickly for normal overlap, but real tasks can take longer than their schedule interval. Suppose an archive begins at 09:00, runs for twelve minutes, and is scheduled every five minutes. The next calendar match comes at 09:05 and the one after at 09:10. Traditional cron does not know whether these command invocations share resources. If all of them update the same report or replace the same files, the order of completion could differ from the order of dispatch. Pick a policy before automating the work.
One policy is to allow independent work when each run has its own input and output. Another is to skip a new invocation when the shared resource is already busy. A system with durable work to complete may need to queue every item for later processing. These are different expectations. For a replaceable inspection summary, skipping a run may be acceptable if the next run is logged. For payroll or a one-time notification, a silent skip could lose required work. The implementation should explain what a skipped or delayed run means to its consumers.
The optional Linux exercise below uses util-linux flock to demonstrate cooperative exclusive locking. A lock in this context is an agreement among processes to acquire the same lock before accessing a shared resource. The small subshell acquires a lock on descriptor nine and then tries a second acquisition through a separate open of the lock path. No sleep or competing schedule is required. The incompatible attempt fails immediately because of -n, and the configured status of 75 lets this exercise identify that particular result. If the command is unavailable in your environment, use the expected evidence without installing it.
if command -v flock >/dev/null 2>&1; then
(
flock -x 9 || exit 1
if flock -n -E 75 "$cron_lab/report.lock" /bin/sh "$cron_lab/report.sh" "$cron_lab"; then
printf 'Unexpectedly acquired a second lock\n'
else
printf 'second acquisition status=%s\n' "$?"
fi
) 9>> "$cron_lab/report.lock"
flock -n -E 75 "$cron_lab/report.lock" /bin/sh "$cron_lab/report.sh" "$cron_lab"
else
printf 'Optional flock exercise skipped\n'
fi
second acquisition status=75
2026-07-01T20:00:00Z workshop-report failures=2
The timestamp is an example. When the subshell closes its descriptor, the initial lock is released, so the next command can acquire its own lock and run the report. A file named report.lock can remain even after the process releases the lock. Its existence is not the proof of an active lock. In real use all cooperating runs must lock the same file identity on a filesystem where the chosen lock semantics work. Avoid removing and recreating a lock path while another job might still hold the original lock, because callers could end up locking different objects.
Lock conflict handling belongs beside the report's other outcomes. If a stage skips because another instance is active, leave a brief diagnostic or accounting record. A lock does not create a retry policy, verify report contents, or make output durable if a job is interrupted. For a file replaced by scheduled work, prepare a complete candidate in a controlled location and publish it only after it passes an appropriate check. Then an interrupted generation can leave the previous good report available. The earlier lesson on redirection explains why opening the final destination immediately can erase it before the writer establishes success.
Find the first missing observation
Start with a missed report at 01:30. Write down the time zone, date, expected owning account, and whether this was a planned one-off or a daily occurrence. Confirm the numeric fields really match that moment using the scheduler's calendar rules. Verify the table you are reading belongs to the intended account and contains the line exactly once. If the daemon was shut down or the machine was off, an ordinary cron entry generally has no distinct catch-up promise. That is a requirement to address in scheduler choice, not an instruction to repeatedly edit the hour field.
Check whether the job was dispatched around that moment. Depending on the installation, scheduler messages may appear in the system journal, a configured log file, or another service's records. On an authorized systemd lab running Cronie, a query for crond.service around the expected time can help. A Debian-family setup may have cron.service instead. Confirm the host's actual service name. A dispatch record is evidence that the scheduler attempted to launch the job, and the report's own log is where you look next for its outcome. Access to either source may be limited by the account used for the test.
When dispatch is present but the log is missing, check the command in the table for the exact log path and directory access. The launching shell normally opens the redirected destination before starting the script. If the directory is missing, the program may never run even though the scheduler invoked the shell. If the log exists and contains Cannot read the inspection input, focus on the script's data path and account. If the log contains a completion line with the wrong count, investigate input validity and calculation. Those three results call for different changes.
When testing manual execution, run as the same authorized account and use an environment close to the scheduled one. Invoking a command through sudo can make an access issue disappear in a way the real job will never see. Similarly, loading your personal shell profile can make a missing path seem correct by accident. Compare interpreter, absolute paths, current directory, file permissions, and relevant environment settings. If tools must be located using the job's own PATH, check the exact directories chosen rather than asking a different interactive shell for a shortcut.
Follow the evidence for duplicate reports too. Look for two matching entries, two schedulers running related jobs, manual executions writing into the same log, and policies that can retry after partial completion. Cross-check each result with its timestamp and an identifier such as the input date. A repeatable job is one you can run again while obtaining an understood result. A job that sends a second email or charges again on retry has different requirements. A scheduler is merely a trigger. Your command must implement or rely on the application's rules for duplicates, recovery, and safe publishing.
Output delivery also varies. Cron implementations may mail output using local mail infrastructure, and a configured MAILTO affects that behavior where supported. If the machine has no such mail delivery or if the output is redirected, do not assume a person will see an error. For a task someone depends on, make failed attempts observable where the team actually checks them. An append-only training log is adequate for two minutes. A job that runs nightly long term needs a retention plan and enough room for its log or managed output stream.
Match the scheduler to what must happen after downtime
For the workshop, a current summary prepared before the opening shift may be enough. If the host was unavailable on Sunday, the staff might want Monday's run to produce the current report. Another department may need to process every inspection batch exactly once, including files received while the machine was off. The two requirements lead to different designs. In the first case a fresh result at the next scheduled run can meet the need. In the second, the system requires a durable list of outstanding work and a way to distinguish completed records from pending ones.
A systemd timer can use calendar conditions with a setting that triggers a catch-up activation if one or more runs were missed while the timer was inactive, when using the documented persistent behavior. Read the Persistent= setting alongside the calendar option. Such a catch-up can activate the associated service once with multiple scheduled moments missed. It does not create a durable per-batch queue. A default paired design uses a timer with one name and a service with the same base name. Observe the timer and the service separately, because timing evidence and the process's success still live in separate places.
The previous service lesson used a oneshot unit that remained active after it exited. That setting helped demonstrate the difference between active and running. A recurring timer normally needs the triggered oneshot to become inactive after it finishes, so that the next occurrence can activate it again. Systemd's timer documentation explains that an already active unit is not restarted when the timer expires. Reading the service definition is therefore part of understanding a recurring timer. This lesson uses a cron-compatible command rehearsal and does not install timer or service units.
For an applied design discussion, suppose the opening shift needs a report at 06:00 local time Monday through Friday, but check-in records can arrive at any time and some days are holidays. A basic weekday schedule can start the command on those weekdays. Holiday policy must come from a maintained calendar or business check, because the weekday field has no concept of a specific holiday. A job can also explicitly identify the report date and refuse to overwrite the same validated report unless the procedure allows a new version. Turning a clock trigger into a reliable business process involves carrying the date and result through the design.
Test both the schedule and the report
First, expand the next few candidate times for 0,20,40 8-9 * * 1-5 on a normal Monday. The six expected times are 08:00, 08:20, 08:40, 09:00, 09:20, and 09:40 in the scheduler's chosen timezone. Check that a Saturday is excluded. Then change the workshop's request to weekday 01:30 India time on a UTC scheduler and write the shifted weekday list. Verify that a 20:00 UTC Sunday instant belongs to 01:30 on Monday in India. The exercise is complete when the fields are explained as calendar values and the day rollover is accounted for.
Second, rehearse the command with the provided fixture and note the expected two failed rows. Add one known failing row to a copy or to the scratch file after saving the original content. Rehearse again with the minimal environment. The successful report should say three failures. Restore the original fixture and run the known good test again. Use separate logs or clearly identify each run in the same append log. If you complete the optional timing observation, remove its entry before changing the file in this exercise so an automatic read does not overlap your manual test.
Third, read the current preview and explain how cron would tokenize it. After the five timing fields, identify the interpreter, its script filename, the directory argument, and both redirections. Say why the time format string stored inside the script does not become crontab special syntax. Finally, simulate a missing input and show the difference between a dispatched command and a completed report. Record the diagnostic and exit status, instead of estimating success from the presence of a log.
After any optional scheduled run is removed, verify its comment and command no longer appear in the personal crontab. Wait for any task you started to finish. Review the generated directory and remove only these known scratch names. The lock filename can be removed at this point because none of this exercise's runs should still hold or need it. If you made additional copies, check their paths and handle them separately before trying to remove the empty parent.
if [ -n "${cron_lab:-}" ] && [ -d "$cron_lab" ]; then
printf 'Removing lesson files in %s\n' "$cron_lab"
rm -f -- "$cron_lab/runs.txt" "$cron_lab/runs.saved.txt" "$cron_lab/report.sh" \
"$cron_lab/manual.log" "$cron_lab/missing.log" "$cron_lab/entry.preview" \
"$cron_lab/cron.log" "$cron_lab/report.lock"
rmdir -- "$cron_lab"
fi
unset cron_lab
Explain a scheduled run from start to finish
Interview question. A script works by hand but fails under cron. What observations do you compare?
Begin with the actual account, schedule timezone, and evidence of dispatch. Once dispatch is known, compare the interpreter, command search path, exact input and output paths, permissions, and required environment settings. A minimal-environment run with a known fixture can reveal assumptions supplied only by the interactive terminal. Keep the job's error log so an execution failure is visible.
Interview question. How would you keep several scheduled report runs from overwriting each other?
First choose whether tasks can run independently, be skipped, or must wait in a durable queue. For a shared report file, cooperating local jobs can use a suitable exclusive lock and generate a candidate before publishing an updated file. Record conflicts and failures separately. A schedule match starts a command without deciding what the command should do when work overlaps.
Quiz. Does */35 in the minute field create a repeating 35-minute interval?
In Cronie's step syntax the selected minutes in each hour are zero and thirty-five. The next run at minute zero of the following hour follows after twenty-five minutes. Expand the calendar filter before relying on an elapsed interval.
Quiz. Which calendar day does 01:30 Monday in India correspond to in UTC?
It is Sunday at 20:00 UTC. An offset of five hours and thirty minutes means the date rolls back when converting this early local time. Verify both the time fields and the applicable day-of-week field.
Quiz. An optional Cronie syntax check passed. Which result shows that the report itself works?
A manual or actual scheduled run with the intended input and environment should return the expected success outcome and show the correct report count. The syntax check validates the table's form. It does not run the program or determine whether the input is available under the scheduled account.
Revision cards
Expand the field values on paper
Write minute, hour, days and timezone separately. Check for steps, mixed day restrictions, and date rollover.
Test the command outside your normal shell
Supply the intended interpreter, working paths, account and environment. Use known good data and a deliberately missing input.
Follow dispatch to the result
Confirm the scheduler launched the job, inspect its log, and verify the data it produced. A table entry only covers the first condition.