每10分钟调用一次PHP函数,持续1小时


call php function every 10mins for 1hour

得到这段代码,应该检查url是否可用,并给我ping:

<?php
function test ($url){
$starttime = microtime(true);
$valid = @fsockopen($url, 80, $errno, $errstr, 30);
$stoptime = microtime(true);
echo (round(($stoptime-$starttime)*1000)).' ms.';
if (!$valid) {
   echo "Status - Failure";
} else {
   echo "Status - Success";
}
}
test('google.com');
?>

我如何使它,所以这个函数将调用每让我们说10分钟1小时(共6次)?

如果您使用Unix服务器或Windows任务调度程序(如果是Windows),我建议您使用cron作业。

像这样,你将能够使用编程任务。

在使用cron的情况下,您可以轻松地这样做:

*/10 * * * *  php -f your_relative_or_full_path_URL/params > /dev/null 

取决于:你想只做一次吗?

然后你可以在循环中调用这个函数,并在每次循环执行后使用sleep()

你想每天都做吗?或者每周/每月的某一天?使用cron

使用一个简单的for循环和sleep命令:

for ($i = 0; $i < 6; $i++) { // Run the code 6 times
    test($url);
    sleep(10 * 60); // Sleep 10 Minutes
}

每月每天发送邮件。我用它来备份日常邮件。

<?php 
  ignore_user_abort(true); //if page is closed its make it live
  for($i=0;$i<=30;$i++)
  {
     $to = "someone@exmple.com";
     $subject = "Test mail $i";
     $message = "Hello! This is a simple email message.";
     $from = "from@example.com";
     $headers = "From:" . $from;
     mail($to,$subject,$message,$headers);
     sleep(24*60);//send mail in every 24 hour. 
}
?>