您的位置:首页 > 运维架构 > Linux

centos使用crontab定时执行php脚本

2017-07-17 14:03 579 查看
首先,找到php安装环境目录,

whereis php  得到目录:假设/opt/lampp/bin/php,记录下来

写好php脚本

require_once("/home/web/wxsq/config.php");
$link = mysqli_connect($host, $user, $pwd ,$dbname);
if (!$link){
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;

die("Connection error: " . mysqli_connect_error());
}
mysqli_query($link,"set character set 'utf8'");//�
mysqli_query($link,"set names 'utf8'");

// $sql="DELETE FROM  `weixin_flag` where  nickname = '李中坤'";
// mysqli_query($link,$sql) or die(mysqli_error($link));

$sql="DELETE FROM  `weixin_flag` where  nickname is null and content is null";
mysqli_query($link,$sql) or die(mysqli_error($link));
这里要注意:

尽量不要用require 和 include, 如果非要用,就要使用绝对路径,而且要保证require或include进来的php没有其他相对目录的引用

不要使用/**/这种注释

编辑crontab

centos 自带crontab。没有的话,要安装

crontab -e 进入编辑模式,点击i,可开始编辑



前面4行是第一次打开就有的,估计是其他定时启动服务,不用管它。

我们enter键另起一行,如图最后一行是我的脚本.

* * * * *5个星星大有学问,同学们可以自己查找使用方法,默认的5个星星就是每1分钟执行一次你配置的脚本。

/opt/lampp/bin/php 是你刚才记录的php环境目录

autoClearData.php是我写的脚本文件

>> /home/...../autoLog1.html 是autoClearData.php的log,这可以用来调试脚本。

crontab不需要重新启动,编辑完成保存好就生效了。

若已经编辑完成,按ESC,再shift+ZZ。完成了

2s频率的定时器自动执行一段小程序。

我的需求是:每秒钟去判断数据库的一个time是否过期,过期就要及时做出处理。

所以呢,crontab可以这么写

方案一:

* * * * * sleep(1) /opt/lampp/bin/php /home/web/funwall/xxxxx.php 

* * * * * sleep(2) /opt/lampp/bin/php /home/web/funwall/xxxxx.php 

........
........

* * * * * sleep(60) /opt/lampp/bin/php /home/web/funwall/xxxxx.php 

这样就要写60次,当然你觉得ok,也可以这么写。但是一个优秀的程序员肯定是受不了这种写法的

方案二:

1,找个目录新建一个crontab.sh,假设我的在/home/web/funwall/crontab.sh

内容:

step=2 #间隔的秒数,不能大于60
for (( i = 0; i < 60; i=(i+step) )); do
$(/opt/lampp/bin/php '/home/web/funwall/xxxxxx.php')
sleep $step
done
exit 0


2,crontab就这么写

* * * * *   /home/web/funwall/crontab.sh

3,在xxxxxx.php写你的程序

这个看代码也知道怎么回事,* * * * * 是1分钟执行一次,而crontab.sh里是一分钟执行30次(可以改的)。

重要:请务必设置crontab.sh为可执行文件; chmod +x crontab.sh
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息