Linux – Cron Jobs for Scheduled Tasks (crontab)

Cron Jobs are automated tasks that you can create in Linux to do such things as delete cache files or run antivirus scans. You simply set when you want the task to run and then type the full command with options.

Notes:

  • Each user has their own crontab file including root.
  • Cron Jobs will have the permissions of the user they are associated with
  • If you accidentally simply Type crontab with no options to exit Type – Control x c together

Crontab Editing and Viewing

  • crontab -e – Edit crontab file for logged in user
  • sudo crontab -e – Edit crontab file for root
  • rm ~/.selected_editor – Resets default crontab editor option
  • crontab -l – Allows you to view crontab file for logged in user
  • crontab -u username -l – Allows you to view crontab file for other user

Crontab Scheduling

  • Format = Minute Hour Day Month DayofWeek Command
  • * * * * * touch /home/bob/cronTestFile = Will touch cronTestFile every minute
  • 00 01 * * * touch /home/bob/cronTestFile = Will touch cronTestFile at 1am every morning
  • https://crontab.guru – Explains scheduling and has interactive tool

1 Comment

  1. The ~/.selected_editor feature seems to be Ubuntu only.

    The more “traditional” way is to set the EDITOR environment variable
    in your shell settings (EDITOR=vim for instance), a lot of tools
    check those variables and use them if set (EDITOR, PAGER being
    the most prominent ones).

    This funny behaviour of just starting ‘crontab’ is most likely due
    to the idea of many Unix commands: you can pipe a crontab into them,
    so this is used to programmatically (shellish) install cronjobs.

    Also systemd timers are going to replace cron completely, so
    it’s maybe not the best idea to learn about crontabs when you
    are new to Linux (though you still have to learn this funny
    0 0 30 * * line syntax, because also systemd timers use it).

    Systemd timers have several advantages, the main one being you can
    have dependend services, so, assume you need a database to do
    a task, you can start up the database just for this cron task
    because systemd timers know about all the dependencies (when you
    configure them, that is).

    One problem I really see is: what should you teach? Because with
    all those systemd things going to replace a 40 year old Linux/Unix userland, it’s really hard to choose.

Leave a Reply