Setup a cron job in linux

Setup a cron job in linux

The cron run processes on the system at the scheduled time. It allows users to run commands or scripts at a given time. if you need to run any script at any specific time. You can set up a cron job and run the file at the scheduled time.

In this article, we will learn how to set up a cron job on the Linux server.

Setup cron Jobs

Run the below command on the terminal to edit the cron file.

crontab -e

If you use the above command without any options, the logged-in user will be edited the crontab by default. If you want to edit the crontab of another user, you have to use the -u option with the above command. Suppose that, you need to edit the crontab file of the user, Tim. Then you need to run the below command.

crontab -u tim -e 

Now we will add our PHP script file to the cron file.

* * * * * php /var/www/html/crons/test_cron.php

According to the given expression, the above file will run every one minute. Please change the path, file name, and expressions according to your need.

Save the file and exit.

Here you have to understand cron schedule expressions.

Minute (0-59)
Hour (0-23)
Day (0-31)
Month (0-12 [12 == December])
Day of the week(0-7 [7 or 0 == sunday])

List Crontab

To view, all crontab entries use the following commands.

crontab -l

If you want to list all crontab entries for the different users. if username is tim.

crontab -u tim -l

Crontab Examples

Here are some examples for scheduling the cron jobs.

Schedule Cron Job Every Minute

* * * * * php /var/www/html/crons/test_cron.php

Schedule Cron Job Every Hour

0 * * * * php /var/www/html/crons/test_cron.php

Schedule Cron Job Every 4 Hour interval

0 */4 * * * php /var/www/html/crons/test_cron.php

Schedule Cron Job at 2 am Every Day

0 2 * * * php /var/www/html/crons/test_cron.php

Schedule Cron Job at every Sunday

0 17 * * sun  php /var/www/html/crons/test_cron.php

Schedule Cron Job Every 1st of the Month

0 0 1 * * php /var/www/html/crons/test_cron.php

Thanks for reading, feel free to reach out to me for any comments and suggestions. I hope you found the article helpful and you were able to set up the cron jobs on the server.

Leave a comment

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