日期:2014-05-16  浏览次数:20573 次

Linux下用Crontab来实现PHP的定时运行<摘录>
1.用PHP编写编写shell
getscore.php
# #!/usr/local/bin/php -q
#     <?
#     $g_dbhost = "localhost";
#     $g_dbname = "1bo8";
#     $g_dbuserid = "root";
#     $g_dbpasswd = "";
#     function opendb(){
#     global $g_dbhost, $g_dbuserid, $g_dbpasswd, $g_dbname, $g_errmsg;
#     $conn = mysql_connect($g_dbhost,$g_dbuserid,$g_dbpasswd);
#     if(!$conn) die($g_errmsg.mysql_error());
#     @mysql_select_db($g_dbname, $conn);
#     if(mysql_errno()) die($g_errmsg.mysql_error());
#     return $conn;
#     }
#     opendb();
#     $date = date("Y-m-d");
#     $time = date("H:i:s");
#     echo $sql = "insert into football_rate set fr_date='$date',fr_time='$time'";
#     $res = mysql_query($sql) or die(mysql_error());
#     ?> 


数据库:
#     CREATE TABLE `1bo8` (
#     `fr_date` date NOT NULL default '0000-00-00',
#     `fr_time` varchar(32) NOT NULL default ''
#     ) ENGINE=innoDB DEFAULT CHARSET=utf8; 


2.设定crontab
执行 vi /etc/crontab 命令

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# run-parts
* * * * * root /home/bjbs270/public_html/getscore.php # 每一分钟执行一次所指定的程序
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly

3.重启crond
/etc/rc.d/init.d/crond start/stop/restart
附:

Crontab是UNIX系统下的定时任务触发器,其使用者的权限记载在下列两个文件中:
/usr/var/adm/cron/cron.deny:该文件中所列的用户不允许使用Crontab命令;
/usr/var/adm/cron/cron.allow:该文件中所列的用户允许使用Crontab命令;
Crontab命令的格式为:crontab –l|-v|-r|-e [username],其参数含义如表一:

参数名称 含义
-l 显示用户的Crontab文件的内容
-v 显示用户的Crontab文件的内容及其提交的时间,只适用于Compaq系列
-r 从Crontab目录中删除用户的Crontab文件
-e 编辑用户的Crontab文件

用户所建立的Crontab文件存于/var/spool/cron/crontabs中,其文件名与用户名一致。
它的格式共分为六段,前五段为时间设定段,第六段为所要执行的命令段,
格式如下:* * * * * <command>

其时间段的含义如表二:

段 含义 取值范围
第一段 代表分钟 0—59
第二段 代表小时 0—23
第三段 代表日期 1—31
第四段 代表月份 1—12
第五段 代表星期几,0代表星期日 0—6


例:如果用户的Crontab文件的内容是:29 19 * * * echo its dinner time,则系统每天的19:29显示‘its dinner time’。
附:当这六段什么都不设的话就是程序在1秒中执行一次
我在用CRON的时候把“01 * * * * 命令1”当成了是每一秒中程序执行一次命令一。这个想法误导了我很久,其实这句话的意思是每个小时的第一分钟程序执行一次。

修改 /etc/crontab 和 crontab -e 指令有何不同?

/etc/crontab 的設定是針對整個系統,只有 root 才有權限修改
crontab -e 的設定是針對個人, 用 crontab -e 建的個人排程會放在 /var/spool/cron/ 下
crontab -e
//編輯排程
crontab -r
// 刪除排程
crontab -l
// 列出排程