Linux Basic — Scheduling with Cron Practice

1 minute read

Practice Exercises — Scheduling with Cron

Work through these to gain fluency with crontab editing, expressions, and logging.


Warm-up

  1. Write a crontab entry to run /opt/hello.sh every minute.
  2. Write an entry for daily at 3:30 AM.
  3. Write an entry for every Monday at 9 AM.
  4. Use @daily shortcut for /opt/backup.sh.

Expressions

  1. Every 15 minutes.
  2. Every 2 hours, but only between 9 AM and 5 PM.
  3. Weekdays only (Mon–Fri) at 8 AM.
  4. First and fifteenth of every month at midnight.
  5. Every Sunday at noon.

Environment & Debugging

  1. Add a cron job that runs env > /tmp/cronenv.txt to see the cron environment.
  2. Set PATH=/usr/local/bin:/usr/bin:/bin in your crontab.
  3. Set MAILTO=you@example.com and confirm cron emails you on job output.
  4. Disable email with MAILTO="".

Logging

  1. Redirect a job’s output to /var/log/myjob.log (append mode, stderr too).
  2. Use logger -t myjob to send output to syslog.
  3. Add a job that logs “hello at $(date)” every minute for 5 minutes, then remove it.

Real Scenarios

  1. Schedule /opt/backup.sh to run daily at 2 AM, logging to /var/log/backup.log.
  2. Schedule /opt/cleanup.sh to run weekly on Sundays at 3 AM.
  3. Use @reboot to run /opt/startup.sh once at boot.
  4. Combine: run a job every 10 minutes during work hours (9–5, Mon–Fri), log to a file, and email on failure.

Verification Checklist

  • All jobs use absolute paths for scripts and commands
  • PATH is set explicitly in crontab if needed
  • Logs use >> to append, not > to overwrite
  • Test each job manually before scheduling
  • Verify jobs run by checking logs or temporary outputs

Next chapter → Clean & Readable Code

Updated: