How to Run Cron Every Minutes, Seconds, Hours, Days, Months – crontab

Cron is a time based scheduler in unix based operating systems. We can use commands, files or shell scripts to run periodically at fixed intervals, times and dates. There are 2 types of cronjob available in every operating system.

1. Root cron job

Users who have ‘sudo’ permission can manage separate root cronjob scheduler.

2. User based cron job

Every users can manage separate crontab file scheduler.

Command:

Display your crontab file:

crontab -l

Create one if it doesn’t already exist / Edit your crontab file:

crontab -e

Remove your crontab file:

crontab -r

Display the last time you edited your crontab file (Only available in few systems):

crontab -v

Syntax:

There are 6 elements in every cronjob scheduling.

minute hour day month week command

Where,

minute – minute value from 0 to 59
hour – hour value from 0 to 23
day – day of month from 1 to 31
month – month from 1 to 12, or name such as jan, feb, etc
week – day of week ( 0-6(Sunday – Saturday) or name such as mon, tue,etc)
command –  command to run

So an example could be this:
0 1 24 5 0 w
That will run a command at 1:00AM on Monday, May 24th. Now that gets a bit cyptic. To make it a little better, this would also work:
0 1 24 may mon w

But what if you want it to run every hour, regardless of date? An “*” means that that field doesn’t matter,
or do the command no matter what is in those fields. So to run our ‘cfile’ command every hour, the command would be this:

0 * * * * cfile

Which means that it runs everyday, every hour at the 0 minute mark, meaning the beginning of the hour.

You can also use commas to specify more than one time.
For instance, say you want to run it at half past the hour, and a quarter of.
You could specify the minute field as this: 30,45

If you use a dash between two values, it will include everything in between them.
An example of this would be to run a command everyday for the first week of a month. The day of the month field would be this: 1-7

So to have the commmand run every 2 hours, at half past and a quarter of, and run for the first 7 days of a month. We would have this:
30,45 */2 1-7 * * w

Example:

Cron job every minute:

Just use asterisk in every part.

* * * * * php cronjob_file.php

Where,

Every minute

Every hour

Every day of the month

Every month

Everyday day in the week

Cron job every 5 minutes:

Just use asterisk in every part except minute section.

*/5 * * * * php cronjob_file.php

Cron job every 5 minutes on Wednesday:

*/5 * 3 * * php cronjob_file.php

Cron job 10:15 AM from Monday to Friday:

15 10 * * 1-5 php cronjob_file.php

Leave a Reply

Your email address will not be published. Required fields are marked *