我试图运行一个php脚本没有cron和成功,但不像我预期的那样工作。我希望脚本每50分钟做一次备份,但它没有这样做,它使它们连续。这是我尝试过的:
cron
<?php
$interval=50; //minutes
set_time_limit(0);
ignore_user_abort(true);
while (true)
{
$now=time();
include("backup.php");
sleep($interval*60-(time()-$now));
}
?>
backup.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$username = "user";
$password = "pass";
$hostname = "dbs";
$dbname = "dbs_name";
// if mysqldump is on the system path you do not need to specify the full path
// simply use "mysqldump --add-drop-table ..." in this case
$dumpfname = $dbname . "_" . date("Y-m-d_H-i-s").".sql";
$command = "mysqldump --add-drop-table --host=$hostname --user=$username ";
if ($password)
$command.= "--password=". $password ." ";
$command.= $dbname;
$command.= " > " . $dumpfname;
system($command);
// zip the dump file
$zipfname = $dbname . "_" . date("Y-m-d_H-i-s").".zip";
$zip = new ZipArchive();
if($zip->open($zipfname,ZIPARCHIVE::CREATE))
{
$zip->addFile($dumpfname,$dumpfname);
$zip->close();
}
// read zip file and send it to standard output
if (file_exists($zipfname)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($zipfname));
flush();
//readfile($zipfname);
//exit;
}
?>
先读一下:PHP注定要死
对于你的问题,你有几件事要考虑:
- 允许
set_time_limit(0);
吗? - 你的服务器也可以有一个单独的最大执行时间
也睡觉,不是很准确(但对于这个用途足够准确)。如果你真的没有权限访问cron,我会检查这两个步骤。如果你有权限访问cron,我真的会考虑使用它(如果你在windows上,看看计划任务)。
一种解决方法是,在每次访客呼叫时,检查文件lastbackup.txt
并检查最后备份时间。如果它比50分钟更早/不可用,您可以在此文件中写入当前时间戳,并在刷新输出后执行备份脚本。
当然,用这种方法它不会每50分钟100%执行一次,但如果不是,也没有什么大的备份
最大执行时间Nginx:
http {
#...
fastcgi_read_timeout 300;
#...
}
Apache:
FastCgiServer /var/www/cgi-bin/php-cgi-5.3.1 -idle-timeout 120
最大执行时间:
<system.web>
<httpRuntime executionTimeout="180" />
</system.web>
也有一个免费的基于web的cron可用:https://cron-job.org/(不知道它是否也在英语上),但我敢肯定,还有更多。