Categories: Development

Creating PHP cron jobs on Ubuntu

Running cron jobs on your Ubuntu server to call PHP scripts in a timely manner.

The first step would be creating a PHP file that when called will leave proof that it was run. This could be creating a text file, doing a log entry or inserting something into a database.

Lets assume /var/html/some.php has

<?php
$myfile = fopen("CRONJOBMADETHIS.txt", "w") or die("Unable to open file!");
$txt = "IT WAS A SUCCESS\n";
fwrite($myfile, $txt);
fclose($myfile);

Which will make a text file when called on.

Next find out where your PHP binary is by using:

whereis php

Depending on how many versions of PHP you have installed the output will show the directories that contain “php” mine was:

It is very common for the directory to be just /usr/bin/php.

crontab

Now to set the cronjob by using crontab

sudo crontab -e

Opens the utility, make your way to the bottom and add the following:

* * * * * /usr/bin/php -f /var/html/some.php

In short this will call some.php every minute.

After a minute of waiting check if the proof was left that it was called. If you used the code above a text file should be made called CRONJOBMADETHIS.txt

If it worked then congratulations, check out crontab guru to learn the timming syntax.

If it did not work, check the cron status with

service cron status

Shows as inactive? start it with

service cron start

View the latest cron tasks by using:

grep CRON /var/log/syslog

If it still isnt working for you try using www-data as the cron user

sudo su -c "crontab -e" www-data

and reapeating the command. Even try just php instead of the full path.

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago