[php] How to create cron job using PHP?

I'm new to using cron job. I don't even know how to write it. I have tried to search from internet, but I still don't understand it well. I want to create a cron job that will execute my code every minute. I'm using PHP to create it. It is not working.


run.php (Code that will be executed every minute)


echo "This code will run every minute";




$path = dirname(__FILE__);
$cron = $path . "/run.php";
echo exec("***** php -q ".$cron." &> /dev/null");


Suppose that these two files are in the same folder.

Is the code that I did wrong? If wrong, please kindly tell me how to fix it.

This question is related to php cron

The answer is

This is the best explanation with code in PHP I have found so far:


In short:

Although the syntax of scheduling a new job may seem daunting at first glance, it's actually relatively simple to understand once you break it down. A cron job will always have five columns each of which represent a chronological 'operator' followed by the full path and command to execute:

* * * * * home/path/to/command/the_command.sh

Each of the chronological columns has a specific relevance to the schedule of the task. They are as follows:

Minutes represents the minutes of a given hour, 0-59 respectively.
Hours represents the hours of a given day, 0-23 respectively.
Days represents the days of a given month, 1-31 respectively.
Months represents the months of a given year, 1-12 respectively.
Day of the Week represents the day of the week, Sunday through Saturday, numerically, as 0-6 respectively.

enter image description here

So, for example, if one wanted to schedule a task for 12am on the first day of every month it would look something like this:

0 0 1 * * home/path/to/command/the_command.sh

If we wanted to schedule a task to run every Saturday at 8:30am we'd write it as follows:

30 8 * * 6 home/path/to/command/the_command.sh

There are also a number of operators which can be used to customize the schedule even further:

Commas is used to create a comma separated list of values for any of the cron columns.
Dashes is used to specify a range of values.
Asterisksis used to specify 'all' or 'every' value

Visit the link for the full article, it explains:

  1. What is the format of the cronjob if you want to enter/edit it manually.
  2. How to use PHP with SSH2 library to authenticate as the user, which crontab you are going to edit.
  3. Full PHP class with all necessary methods for authentication, editing and deleting crontab entries.

Similar questions with php tag:

Similar questions with cron tag: