Linux Training : j. Automating tasks with cron

Automating tasks with cron

cron is a way to have code run at a certain time on a regular basis.

  • Log files get rotated daily due to a system-wide cron process.
  • Each user has their own cron process. crontab -l will show a user's cron job listing while crontab -e will edit it using LIN:vi.

crontab syntax

The syntax of a cron entry is pretty simple as there are only 6 fields. The first 5 are space delimited and are for minute, hour, day of month, month, day of week. The last field continues to the end of the line and is for the command to be run at the time specified in the first 5 fields.

  • The time and date fields

    field

    allowed values

    minute

    0-59

    hour

    0-23

    day of month

    1-31

    month

    1-12 (or names, see below)

    day of week

    0-7 (0 or 7 is Sun, or use names)

  • The system cron looks like:

    01 * * * * root run-parts /etc/cron.hourly
    02 4 * * * root run-parts /etc/cron.daily
    22 4 * * 0 root run-parts /etc/cron.weekly
    42 4 1 * * root run-parts /etc/cron.monthly
    
  • A field with a * means from first to last.
  • Lists are allowed values for numerical fields as well:
    • 1,4,7,10,36
  • step values:
    • 1-9/2 in the hour field means every 2 hours from 1 am until 9 am.
  • Month and day of week can also use names where the first three characters are enough.
    • Weekdays are numbered 0-7 with Sunday as both 0 and 7.
      If there are two ways to designate a time such as day of month and day of week, be aware that this is an +OR+ process not an +AND+.

      example:

      30 4 1,15 * 5 somescript
      

      will cause the event somescript to occur both on the 1st and fifteenth each month but also every Friday.


  • By default, a cron process will send a status email to the controlling user. This can be changed with a line in the crontab of MAILTO='<username>' or MAILTO='' to have no email sent.

    When cron runs a script, by default that process is run with no use of bashrc, no PATH, nothing.

  • The environment for cron scripts is different from how they were tested.
    • Always use full pathing
    • Directly specify any shell variable and do not assume they are valid otherwise. cron does know $HOME for the username it runs as so it's easy to add a . ~/.bashrc at the top of any cron script.
cron exercise
  1. Write a bash script that will record a timestamp to a file if your username is currently logged in. Have your cron run this script every 10 minutes on weekdays.
  2. Write a second script that will log to a second file the number of entries in the first file on a daily basis and then remove the first file. This should run once per day.
  3. Lastly, write a script that will clean up all of the second scripts files older than 2 days. This should run once per day as well.