logo
. . .

How to setup cron jobs in Ubuntu

 

  1. Access the Crontab:
    • Open a terminal on your Ubuntu system.
  2. Edit the Crontab File:
    • To edit the crontab file for the current user, type the following command:
      crontab -e
    • If you want to edit the crontab file for a specific user (assuming you have the necessary permissions), you can use:
      crontab -u username -e

    Replace “username” with the actual username.

  3. Cron Syntax:
    • The crontab file uses a specific syntax to define the schedule. It consists of five fields, representing minute, hour, day of the month, month, and day of the week. An asterisk (*) denotes any value in that field.
      * * * * * command_to_be_executed
    • For example, 0 2 * * * means the command will run at 2:00 AM every day.
  4. Examples:
    • Here are some examples of common cron job schedules:
      • Run a script every day at 3:30 AM:
        30 3 * * * /path/to/script.sh
      • Run a command every hour:
        0 * * * * /path/to/command
      • Run a command every Monday at 4:45 PM:
        45 16 * * 1 /path/to/command
  5. Save and Exit:
    • After making your changes, save and exit the crontab editor.
      • For nano editor: Press Ctrl + X to exit, then press Y to confirm changes, and press Enter.
      • For vim editor: Press Esc to make sure you are in command mode, then type :wq and press Enter.
  6. Viewing Crontab:
    • To view the current user’s crontab entries, use:
      crontab -l

      For a specific user:

      crontab -u username -l
  7. Common Issues:
    • Ensure that the paths to scripts or commands in your cron job are absolute paths.
    • Check the cron log for any error messages. You can view the cron log using:
      grep CRON /var/log/syslog
  8. Verify Execution:
    • Wait for the scheduled time, and the specified command or script should execute. You can also manually trigger the cron job using:
      run-parts /etc/cron.daily

That’s it! You’ve successfully set up cron jobs on your Ubuntu system. Remember to test your cron jobs to ensure they’re running as expected.