Categories
Linux MAC UNIX

cronjob

Welcome back to another round of nerd. Have you ever wanted to learn about cronjobs? Then you’ve come to the right place for a basic overview.

Wikipedia – “cron is a time-based job scheduler in Unix-like computer operating systems. cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates. It is commonly used to automate system maintenance or administration.

So where was I? Oh yeah, cronjobs.

The basics

Read the man pages.

Man pages: cron(8) crontab(5) crontab(1)

$ man 8 cron
$ man 5 crontab
$ man crontab

List your crontab

$ crontab -l

List a users crontab

$ crontab -l -u

Example:

$ sudo crontab -l -u root

Remove your crontab(s)

$ crontab -r

Syntax

* * * * * command to be executed
– – – – –
| | | | |
| | | | —– Day of week (0 – 7) (Sunday=0 or 7)
| | | ——- Month (1 – 12)
| | ——— Day of month (1 – 31)
| ———– Hour (0 – 23)
————- Minute (0 – 59)

Editing crontab

Edit your personal crontab:

$ crontab -e

OR

Edit another users crontab

$ sudo crontab -e -u

Example:

$ sudo crontab -e -u root

Note: Use root when you want to run a command that involves sudo.

Format

Now that we know where to add a cronjob, lets learn the format. Nothing is better than just showing you the exact commands.

Runs at startup

/path_to_script_or_command

Runs every 5 minutes

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /path_to_script_or_command

or

*/5 * * * * /path_to_script_or_command

Runs every hour

0 * * * * /path_to_script_or_command

Runs every day (at midnight)

0 0 * * * /path_to_script_or_command

Runs every week

0 0 * * 0 /path_to_script_or_command

Runs every month

0 0 1 * * /path_to_script_or_command

Runs every year/annually

0 0 1 1 * /path_to_script_or_command

But Tommy, I wish there was just a simple generator where I can plug in exactly what I want and get those numbers generated for me automatically. Well, you’re in luck.

http://www.generateit.net/cron-job

My real world example

If you read my “Mac Terminal Loading Slow” post, you’ll notice that you’d need to clear the logs every week/month or so. I wanted to automate this task. I couldn’t place the sudo rm -f /private/var/log/asl/*.asl command in my .bash_* due to sudo. Actually, I could have, but I didn’t want to enter my password every time it ran (who would want to do that?). So I decided to add the command directly into a cronjob and run it every week. Also, since it’s a sudo command, I am adding it to the user root‘s crontab.

$ sudo crontab -e -u root
0 0 * * 0 rm -f /private/var/log/asl/*.asl

Note: I no longer have to use sudo because root has an all access pass to do everything it wants.

You should understand the basics of how to create a cronjob. Now get out there and automate something and make your life that much easier. Remember, never work hard, work smart.

Comments

By Tommy Elmesewdy

DevOps Engineer

2 replies on “cronjob”