Cron is a time-based job scheduler in Unix-like operating systems like Linux. It allows you to schedule tasks (cron jobs) to run at specific intervals or times. You can use cron jobs to automate tasks like updating a database, generating reports, or sending scheduled emails.
To set up a cron job with PHP, you can follow these steps:
1. First, you need to create a PHP script that contains the code you want to run as a cron job. For example, let’s say you have a script called `send_email.php` that sends an email to all users every day at 8 AM.
“`php
“`
2. Next, you need to set up a cron job to run this script at the desired interval or time. Open your terminal and enter the following command to edit the crontab file:
“`shell
crontab -e
“`
This will open the crontab file in your default text editor.
3. In the crontab file, add a new line for your cron job. The format of a cron job entry is:
“`
* * * * * command-to-be-executed
“`
The five asterisks represent the schedule for the cron job, in the order of minutes (0-59), hours (0-23), day of month (1-31), month (1-12), and day of week (0-7, where both 0 and 7 represent Sunday).
To schedule the `send_email.php` script to run every day at 8 AM, you can add the following line to the crontab file:
“`
0 8 * * * /usr/bin/php /path/to/send_email.php
“`
This line specifies that the script should run at 8 AM (0 minutes, 8 hours) every day.
4. Save the crontab file and exit the text editor.
Now, the `send_email.php` script will be executed automatically by the cron job at the specified time. You can check the output or any error logs by redirecting the output to a file or by sending the output via email.
Note: Make sure to replace `/path/to/send_email.php` with the actual path to your PHP script.
That’s it! You have now set up a cron job with PHP. You can add more cron jobs to the crontab file by repeating the steps above.