php定时任务

sent_mail.php 启动程序
stop_mail.php 停止程序
mail_log.txt    程序日志,邮件发送记录
status.txt  储存状态,是否发送

sent_mail.php

<?php
header("Content-type: text/html; charset=utf-8");
	
	function setEmail(){
		
		//链接数据库	
		$fp=@fopen("mail_log.txt","a+");//打开邮件发送记录log文件
		$status = mail($to,$subject,$message,$headers);
		
			if ($status) {
				$numb_1++;
				fwrite($fp,date("Y-m-d H:i:s")." Success !
");//邮件发送成功记录
			}else{
				$numb_0++;
				fwrite($fp,date("Y-m-d H:i:s")." Error!
");//邮件发送失败记录
			}		
			
		}
		
		fclose($fp);//关闭邮件发送记录log文件
		//关闭数据库
		
		return array($numb_0,$numb_1);
	}
	
	file_put_contents("status.txt","yes");
	$status=file_get_contents("status.txt");
	if(!$status==""){
		
	 	ignore_user_abort();//无视关闭浏览器	
		set_time_limit(0);//程序永久执行,除非停止服务器
		$i=1;
		do{
			$status=="";
			$status=trim(file_get_contents("status.txt"));
			if($status=="yes"){
				try{
					if(($numb=setEmail())==false){
						$logstr="The program has been executed ".$i." times --> no email sent 
 ---------------------------------------------------
";
					}else{
						$logstr="The program has been executed ".$i." times --> Number of email sent: succeed(".$numb[1]."), fail(".$numb[0].") 
 ---------------------------------------------------
";
					}
				}catch(Exception $e){
					$logstr="The program has been executed ".$i." times --> Send email program error:".'Message: ' .$e->getMessage()." 
 ---------------------------------------------------
";
				}
				$fp=@fopen("mail_log.txt","a+");
				fwrite($fp,$logstr);
				fclose($fp);
				$i++;
			}
			for ($j = 0; $j < 24; $j++) {
				if(trim(file_get_contents("status.txt"))=="yes"){
					sleep(60*60);
				}else{
					$fp=@fopen("mail_log.txt","a+");
					fwrite($fp,date("Y-m-d H:i:s")."The program has been stopped!");
					fclose($fp);
					die("Timing tasks has been closed!");
				}
			}
		}while(true);
		
	}else{
		die("Read status.txt file error, the program shut down!");
	}
}
die();

 stop.php

file_put_contents("status.txt","no");
原文地址:https://www.cnblogs.com/jevil/p/3467952.html