How to run Cron jobs in PHP?

Better Stack Team
Updated on October 5, 2023

To run Cron jobs in PHP, you can create a PHP script with the code you want to run and schedule it to run using Cron. Here are the steps to create and schedule a PHP script:

🔭 Want to get alerted when your Cron doesn’t run correctly?

Go to Better Stack and start monitoring in 5 minutes.

Create the PHP script

Create a PHP script with the code you want to run as a Cron job. I can look something like this:

// ...
// Send reminder email to users
foreach ($users as $user) {
    $to = $user['email'];
    $subject = 'Reminder';
    $message = 'Hello, ' . $user['name'] . '! This is a reminder.';
    mail($to, $subject, $message);

Set the correct file permissions:

Make sure that the file permissions of your PHP script allow the user running the Cron job to execute it. You can set the permissions using the chmod command:

chmod +x reminder.php

Schedule the Cron job:

Open the crontab file using the command crontab -e and add the following line to schedule the Cron job:

0 9 * * * /usr/bin/php /path/to/reminder.php

This Cron job will run every day at 9am and execute the reminder.php script using the PHP interpreter located at /usr/bin/php.

Verify the Cron job:

You can verify that the Cron job has been added to the crontab file by running the following command:

crontab -l

By following these steps, you can create and schedule a PHP script to run as a Cron job.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github