Running Cron Job on Ubuntu - Quick Reference and Simple Examples

Running Cron Job on Ubuntu - Quick Reference and Simple Examples

Last updated:
Table of Contents

cron is the default way to schedule jobs (shell scripts and/or commands) and make them run repeatedly in a defined manner on any Unix-based OS.

Here are some quick examples on how to use it:

Edit cron configuration

After you finish editing, make sure you close the file or changes won't take effect. (For example, if on vim, don't just use :w to save, use :wq to save and close the file).

$ crontab -e

For commands you need to run as root, you need to open crontab as root too:

$ sudo crontab -e

Run command every day at the same time

For example, run /home/path/to/command every day at 2:30 AM

# other jobs here
30 2 * * * /home/path/to/command

view cron logs

Cron events (command runs and configuration edits) are logged to /var/log/syslog so you can use grep to filter cron messages:

$ cat /var/log/syslog | grep -i cron

Output:

Sep 28 19:11:01 felipe-Inspiron-7559 CRON[19229]: (felipe) CMD (/home/felipe/memory-temperature-check)
Sep 28 19:12:01 felipe-Inspiron-7559 CRON[19262]: (felipe) CMD (/home/felipe/foo-bar-baz)
Sep 28 19:12:01 felipe-Inspiron-7559 CRON[19263]: (felipe) CMD (/home/felipe/memory-temperature-check)
...

View command output/errors

Standard output and standard error for jobs doesn't usually go to syslog unless you enable it yourself.

The fix is to modify the command so that it logs everything to a file:

# other jobs here ...
# the following job will not log errors if there are problems
* * * * * /home/username/script-with-errors
# the following job will log output and errors to cron.out
* * * * * /home/username/script-with-errors >> /home/username/cron-output-error 2>&1

Run job as another user

One way is to directly edit another user's crontab with crontab -u (if you have root privilege, obviously)

$ sudo crontab -u other_user -e