如何使用 PHP 创建 cron 作业?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18737407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:07:28  来源:igfitidea点击:

How to create cron job using PHP?

phpcron

提问by user2738520

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.

我是使用 cron 工作的新手。我什至不知道怎么写。我试图从互联网上搜索,但我仍然不太明白。我想创建一个 cron 作业,每分钟执行一次我的代码。我正在使用 PHP 来创建它。它不工作。

Example

例子

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

run.php (每分钟执行一次的代码)

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

我做的代码错了吗?如果错了,请告诉我如何修复它。

回答by Nikolay Ivanov

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

这是迄今为止我发现的 PHP 代码的最佳解释:

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

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:

虽然安排新作业的语法乍一看似乎令人生畏,但一旦分解它,实际上理解起来相对简单。cron 作业将始终有五列,每列代表一个按时间顺序排列的“运算符”,后跟完整路径和要执行的命令:

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

* * * * * 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:

因此,例如,如果有人想在每个月的第一天的凌晨 12 点安排一项任务,它看起来像这样:

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

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:

如果我们想安排一个任务在每周六早上 8 点 30 分运行,我们可以这样写:

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

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.
  1. 如果要手动输入/编辑 cronjob 的格式是什么。
  2. 如何使用 PHP 和 SSH2 库以用户身份进行身份验证,您将编辑哪个 crontab。
  3. 完整的 PHP 类,包含用于身份验证、编辑和删除 crontab 条目的所有必要方法。

回答by Alister Bulman

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.

与您尝试运行 cron.php 的方式相同,您可以运行另一个 PHP 脚本。不过,您必须通过 CLI 界面执行此操作。

#!/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:

然后,在 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:

如果 run.php 脚本有可执行权限,它可以直接列在 crontab 中,也没有 /usr/bin/php 部分。脚本中的“env php”部分会找到合适的程序来实际运行 PHP 代码。因此,对于“可执行”版本 - 向文件添加可执行权限:

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

and then, add the following entry into crontab:

然后,将以下条目添加到 crontab 中:

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

回答by Big Ginger Nerd

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

添加到 Alister,您可以通过在服务器上的 ssh 会话中输入 crontab -e 通常(并非总是如此)来编辑 crontab。

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.

您可以在此处阅读更多相关信息。

回答by madhu131313

Type the following in the linux/ubuntu terminal

在 linux/ubuntu 终端中输入以下内容

 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

回答by Ecko Santoso

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

为什么不使用 curl?从逻辑上讲,如果您执行 php 文件,您将在浏览器上通过 url 执行该文件。如果你运行 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);
}

回答by acharris

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.

如果您不托管自己的内容,这可能取决于您的网络托管服务商。如果您的网络主机支持创建 chron 作业,他们可能会提供一个表格供您填写,让您选择频率并输入要执行的文件的绝对路径。例如,我的网络主机 (DreamHost) 允许我通过输入文件的绝对路径并从选择菜单中选择频率来创建自定义 cron 作业。这可能不适用于您的服务器,在这种情况下,您需要直接或通过主机特定的方法编辑 crontab。

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

正如上面的Alister Bulman详细说明的那样,创建一个 PHP 文件以使用 CLI 运行(确保#!/usr/bin/env php在文件的最开始处包含在<?php标记之前。这确保 shell 知道在运行脚本时应该调用哪个可执行文件。

回答by shubhi agrawal

$command = "php ".CRON_PATH.php ";
if(substr(php_uname(), 0, 7) == "Windows"){
pclose(popen("start /B ". $command, "r"));
}else{
shell_exec($command ." > /dev/null &");
}

回答by Gokulpriya

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,

首先使用用户名和密码打开您的 SSH 服务器并更改为默认的 root 用户(具有所有权限的用户),然后按照以下步骤操作,

  1. enter the command crontab -lnow you will see the list of all cronjobs.
  2. enter crontab -ea file with all cron jobs will be opened.
  3. Edit the file with your cronjob schedule as min hr dayofmonth month dayofweek pathtocronjobfileand save the file.
  4. Now you will see a response crontab: installing new crontabnow again check the list of cronjobs your cron job will be listed there.
  1. crontab -l现在输入命令,您将看到所有 cronjob 的列表。
  2. 输入crontab -e一个包含所有 cron 作业的文件将被打开。
  3. 使用您的 cronjob 计划编辑文件min hr dayofmonth month dayofweek pathtocronjobfile并保存文件。
  4. 现在您将crontab: installing new crontab再次看到响应,检查您的 cron 作业将在那里列出的 cronjobs 列表。

回答by rams0610

Create a cronjob like this to work on every minute

创建一个像这样的 cronjob 每分钟都在工作

*       *       *       *       *       /usr/bin/php path/to/cron.php &> /dev/null

回答by maxkuku

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

有一个简单的方法可以解决这个问题:您可以每 1 分钟通过 cron 执行一次 php 文件,并且在 php 可执行文件中制作“if”语句以在时间“现在”时执行,如下所示

<?/** 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 */
}