118

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.

Example

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

<?php

echo "This code will run every minute";

?>

cron.php

<?php

$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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user2738520
  • 1,341
  • 4
  • 13
  • 17
  • do you have shell access on the server? –  Sep 11 '13 at 09:31
  • 10
    You can't just echo out *** and expect a cronjob to be created. Read up here how to create cronjobs (assuming you are on a server running linux) http://www.thesitewizard.com/general/set-cron-job.shtml – tlenss Sep 11 '13 at 09:31
  • @Dagon: i don't know about this. I'll check it out. – user2738520 Sep 11 '13 at 09:40
  • It is a one off event so use `crontab` – Ed Heal Jan 26 '14 at 16:49
  • @user2738520 Where did you get the idea of naming the file `cron.php`? A [cron job](https://en.m.wikipedia.org/wiki/Cron) is a job being run by the operating system, so it needs to be registered there. BUT, I saw that f.e. the CMS Contao would have its own hack around this for web masters who don’t have server access. They include a `cron.php` in every page view and then have their own scheduling logic. Is this the case for you? – Andy Jun 20 '22 at 08:54

11 Answers11

78

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

http://code.tutsplus.com/tutorials/managing-cron-jobs-with-php--net-19428

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.
Nikolay Ivanov
  • 5,159
  • 1
  • 26
  • 22
42

In the same way you are trying to run cron.php, you can run another PHP script. You will have to do so via the CLI interface though.

#!/usr/bin/env php
<?php
# This file would be say, '/usr/local/bin/run.php'
// code
echo "this was run from CRON";

Then, add an entry to the crontab:

* * * * * /usr/bin/php -f /usr/local/bin/run.php &> /dev/null

If the run.php script had executable permissions, it could be listed directly in the crontab, without the /usr/bin/php part as well. The 'env php' part, in the script, would find the appropriate program to actually run the PHP code. So, for the 'executable' version - add executable permission to the file:

chmod +x /usr/local/bin/run.php

and then, add the following entry into crontab:

* * * * * /usr/local/bin/run.php &> /dev/null
Alister Bulman
  • 34,482
  • 9
  • 71
  • 110
12

Added to Alister, you can edit the crontab usually (not always the case) by entering crontab -e in a ssh session on the server.

The stars represent (* means every of this unit):

[Minute] [Hour] [Day] [Month] [Day of week (0 =sunday to 6 =saturday)] [Command]

You could read some more about this here.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
5

Better use the project Cron in combination with the Linux cronjob for this task. It allows you to configure run times in your PHP Code, support background jobs and is easy to use.

First step call a PHP Script every minute:

* * * * * /usr/local/bin/run.php &> /dev/null

Second Step use the cron/cron Package to configure run times directly in PHP.

$deprecatedStatus = new ShellJob();
$deprecatedStatus->setCommand('cd /app && /usr/local/bin/php cron/updateDeprecatedStatus.php');
$deprecatedStatus->setSchedule(new CrontabSchedule('* * * * */2'));


$displayDate = new ShellJob();
$displayDate->setCommand('cd /app && /usr/local/bin/php cron/updateDisplayDate.php');
$displayDate->setSchedule(new CrontabSchedule('* * * * */5'));

You found the details how to use in the linked repository.

Thomas Eimers
  • 395
  • 5
  • 5
4

Type the following in the linux/ubuntu terminal

 crontab -e 

select an editor (sometime it asks for the editor) and this to run for every minute

*       *       *       *       *       /usr/bin/php path/to/cron.php &> /dev/null
madhu131313
  • 7,003
  • 7
  • 40
  • 53
1

That may depend on your web host if you are not hosting your own content. If your web host supports creating chron jobs, they may have a form for you to fill out that lets you select the frequency and input the absolute path to the file to execute. For instance, my web host (DreamHost) allows me to create custom cron jobs by typing in the absolute path to the file and selecting the frequency from a select menu. This may not be possible for your server, in which case you need to either edit the crontab directly or through your host specific method.

As Alister Bulman details above, create a PHP file to run using CLI (making sure to include #!/usr/bin/env php at the very start of the file before the <?php tag. This ensures that the shell knows which executable should be invoked when running the script.

acharris
  • 31
  • 4
0

First open your SSH server with username and password and change to the default root user(User with all permissions) then follow the steps below,

  1. enter the command crontab -l now you will see the list of all cronjobs.
  2. enter crontab -e a file with all cron jobs will be opened.
  3. Edit the file with your cronjob schedule as min hr dayofmonth month dayofweek pathtocronjobfile and save the file.
  4. Now you will see a response crontab: installing new crontab now again check the list of cronjobs your cron job will be listed there.
-3

Create a cronjob like this to work on every minute

*       *       *       *       *       /usr/bin/php path/to/cron.php &> /dev/null
rams0610
  • 1,041
  • 10
  • 8
  • 6
    I think we are looking solutions to create cronjob using php and not using any terminal or cpanel. I also want to find this solutions using php only. – user3264863 Aug 11 '16 at 10:41
-3
function _cron_exe($schedules) {
        if ($obj->get_option('cronenabledisable') == "yes") {
            // $interval = 1*20;
            $interval = $obj->get_option('cronhowtime');
            if ($obj->get_option('crontiming') == 'minutes') {
                $interval = $interval * 60;
            } else if ($obj->get_option('crontiming') == 'hours') {
                $interval = $interval * 3600;
            } else if ($obj->get_option('crontiming') == 'days') {
                $interval = $interval * 86400;
            }
            $schedules['hourlys'] = array(
                'interval' => $interval,
                'display' => 'cronjob'
            );
            return $schedules;
        }

}
Ranjith
  • 165
  • 15
-3

There is a simple way to solve this: you can execute php file by cron every 1 minute, and inside php executable file make "if" statement to execute when time "now" like this

<?/** suppose we have 1 hour and 1 minute inteval 01:01 */

$interval_source = "01:01";
$time_now = strtotime( "now" ) / 60;
$interval = substr($interval_source,0,2) * 60 + substr($interval_source,3,2);


if( $time_now % $interval == 0){
/** do cronjob */
}
maxkuku
  • 188
  • 4
  • 7
-3

why you not use curl? logically, if you execute php file, you will execute that by url on your browser. its very simple if you run curl

while(true)
{
    sleep(60); // sleep for 60 sec = 1 minute

    $s = curl_init();
    curl_setopt($s,CURLOPT_URL, $your_php_url_to_cron); 
    curl_exec($s); 
    curl_getinfo($s,CURLINFO_HTTP_CODE); 
    curl_close($s);
}
Ecko Santoso
  • 500
  • 4
  • 10
  • 7
    This would work in theory but the php-script would have to run all the time which is not a good thing. – bestprogrammerintheworld Jan 06 '18 at 11:45
  • 3
    You have to set php-max-execution-time to be 0 in order to run this forever. Also if some error occurs in your script, it wont execute again until you restart it manually. – Hassan Raza Nov 19 '18 at 12:10