本文介绍下,在php中借助crontab,进行自动运行相关程序的方法,有需要的朋友,参考下吧。crontab-操作每个用户的守护程序和该执行的时间表。具体的部分参数说明如下:
crontab file [-u user]-用指定的文件替代目前的crontab。 crontab-[-u user]-用标准输入替代目前的crontab. crontab-1[user]-列出用户目前的crontab. crontab-e[user]-编辑用户目前的crontab. crontab-d[user]-删除用户目前的crontab. crontab-c dir- 指定crontab的目录。 crontab文件的格式:m h d m d cmd. m: 分钟(0-59)。h:小时(0-23)。d:天(1-31)。m: 月(1-12)。 d: 一星期内的天(0~6,0为星期天)。 cmd要运行的程序,程序被送入sh执行,这个shell只有user,home,shell这三个环境变量。
下面是一些具体的应用实例,供大家参考。
复制代码 代码示例:#min hour day month dayofweek command #每天早上6点 106* * * date#每两个小时 0*/2* * * date#晚上11点到早上8点之间每两个小时,早上部点 0 23-7/2,8* * * date#每个月的4号和每个礼拜的礼拜一到礼拜三的早上11点 0 11 4* mon-wed date#1月份日早上4点 0 4 1 jan* date 范例 lark:~>crontab-1 列出用户目前的crontab. #min hour day month dayofweek command 10 6* * * date 0*/2* * * date 0 23-7/2,8 * * * datelinux中使用crontab必须特别注意环境变量问题,在此以执行oracle的sqlplus为例, 说明crontab的使用方法。1,crontab 使用方法: crontab [ -e | -l | -r ] 文件名 -e:编辑任务 -l:显示任务信息 -r:删除定时执行任务信息2,crontab中处理的文件格式为 分钟 小时 日期 月 星期 执行的文件名 *代表所有条件 5 * * * * rem /home/oracle/execsql 代表每个小时的5分钟时执行/home/oracle/execsql文件3,对于sql等需要在特定的环境变量下运行的命令,在执行文件中必须列出。 如在oracle下执行sqlplus,必须按以下格式编写: $ cat execsql oracle_home=/ora815;export oracle_home oracle_owner=oracle;export oracle_owner oracle_sid=ora815;export oracle_sid oracle_base=/ora815/app/oralce;export oracle_base ld_library_path=$oracle_home/lib;export ld_library_path path=$path:$oracle_home/bin:$ld_library_path;export path nls_lang=american_america.zhs16cgb231280;export nls_lang /ora815/bin/sqlplus test1/test1 @test1.ext (执行@test1.ext文件,数据库的用户名/密码为test1/test1)其中要求execsql为可执行的程序 $ ls -al execsql -rwxr-xr-x 1 oracle dba 374 oct 07 15:17 execsql使用crontab,使php程序在12:00运行就按照下面的格式改一下,加在crontab就行了00 0 * * * cd /你的程序路径;php 你的程序名字.php这个需要编译的时候有cli或者cgi模式的php。
另外:若无管理权限,只有虚拟空间php里有个函数很有用。这是在最近的开发中才逐渐用到的。 int ignore_user_abort ( [bool setting] ) 这个函数的作用是指示服务器端在远程客户端关闭连接后是否继续执行下面的脚本。 setting 参数是一个可选参数。如设置为true,则表示如果用户停止脚本运行,仍然不影响脚本的运行(即:脚本将持续执行);如果设置为false,则表示当用户停止运行脚本程序时,脚本程序将停止运行。
php后台执行任务的代码:
复制代码 代码示例: