不使用CRON安排脚本

Nic*_*ard 15 php scripting cron command-line-interface

我知道有很多关于使用CRON运行php文件的帖子.但是,在共享托管的世界中,以及用户的易于设置,我不想让它搞乱.

我在网上发现了另一个与套接字有关的解决方案.只是想让每个人都接受这个,并告诉我这是一个好主意还是坏主意.听起来很有效.

思考?

//Open socket connection to cron.php
$socketcon = fsockopen($_SERVER['HTTP_HOST'],80,$errorno,$errorstr,10);
if($socketcon) {
$socketdata = "GET /cron.php HTTP 1.1\r\nHost: ".$_SERVER['HTTP_HOST']."\r\nConnection: Close\r\n\r\n";
fwrite($socketcon,$socketdata);
//Normally you would get all the data back with fgets and wait until $socketcon reaches feof.
//In this case, we just do this:
fclose($socketcon);
} else {
//something went wrong. Put your error handler here.
}
Run Code Online (Sandbox Code Playgroud)

cron.php:

//This script does all the work.
sleep(200);
//To prove that this works we will create an empty file here, after the sleep is done.
//Make sure that the webserver can write in the directory you're testing this file in.
$handle = fopen('test.txt','w');
fclose($handle);
Run Code Online (Sandbox Code Playgroud)

从博客文章中找到该脚本:http://syn.ac/tech/13/creating-php-cronjobs-without-cron-and-php-cli/

gho*_*g74 5

一个 cron 作业基本上就是一个 cron 作业。您进行设置,操作系统就会为您运行该作业。我不确定您从网站获得的 PHP 脚本是如何工作的,但如果它需要人工干预,那么它并不是真正的 cron 作业。如果你不想使用cron,你可以使用循环,然后使用PHP的日期函数来设置日期和时间。伪代码

while (1) {
    $d=date("d");
    if ( $d == "01" ){
        //run every 1st of month
        //code to run here
    }
}
Run Code Online (Sandbox Code Playgroud)


Xor*_*lev 4

这不是一个坏方法,但您需要确保通过关闭套接字不仅仅是在脚本完成之前终止脚本。您可以将套接字设置为非阻塞。

我仍然会使用 cron 作业,即使它有点痛苦。

  • @Bill Karwin - 因为轮子实际上是方形的。:) (5认同)