My first cron job

The first thing I did was, I added a check in the header.php:

if ( isset($_GET['mycronjob'])) {
	$date = date('Y-m-d H:i:s');
	file_put_contents("test.txt", $date );

	myFunction(); 
}

The first two lines inside of the if statement outputs a test.txt into the same folder as header.php with the time and date. (so I can check that the cron job is doing something)

After that it runs myFunction.

To make this code to run, you have to enter this address in your browser: https://www.example.com/?mycronjob, and that will trigger the content inside of the if statement.

So after that i logged into the server as a user and run this command:

crontab -e

And then I added the following to the file and saved it:

0 * * * * curl --request GET 'https://www.example.com/?mycronjob' >/dev/null 2>&1

This means that it will ‘visit’ this site ones every hour (at 1200, 1300, 1400 and so on). The last part (/dev/null 2>&1) means that it wouldn’t send out any mail to the server admin.

Here are some ‘nice to know’ command you can use instead of ‘0 * * * *’:

Special stringMeaning
@rebootRun once, at startup.
@yearlyRun once a year, “0 0 1 1 *”.
@annually(same as @yearly)
@monthlyRun once a month, “0 0 1 * *”.
@weeklyRun once a week, “0 0 * * 0”.
@dailyRun once a day, “0 0 * * *”.
@midnight(same as @daily)
@hourlyRun once an hour, “0 * * * *”.

Leave a Reply

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