CentOS 下管理自定义 PHP 计划任务代码的守护进程脚本
from http://micate.me/centos-php-crontab-script-manage-shell.note « javascript dialog 对话框的问题总结MySQL的表分区 »CentOS 下管理自定义 PHP 计划任务代码的守护进程脚本 Version: 2011-12-05 Print Published at 02:45 in 技术. 2 Comments Tags: centos, php, 计划任务. 有需求想实现比 crontab 更频繁一点的计划任务,折腾一通之后,写下这个脚本,目前在 CentOS 6 下测试没有问题:
ChangeLog 2011.12.05 添加 PHP 执行用户设置,用以适应如在计划任务中执行生成文件操作时的文件权限问题,未完成; 2011.12.02 建立文档; Shell 代码 #!/bin/bash
chkconfig: 35 90 12
description: Queue Daemon
Get function from functions library
. /etc/init.d/functions
PHP 访问路径,如果 PHP 是编译安装则需要修改
php_path="/usr/bin/php"
PHP 执行用户名
Nginx 环境下常见为 nginx 或 www,
Apapche 环境下常见为 php 或 apache
用在某些时候需要在计划任务中生成文件时文件权限不正确的问题
php_user=nginx
要管理的 PHP 计划任务脚本
该目录下必须都是 PHP 可执行代码文件
queue_path="/www/micate.dev/crontab/"
PHP 计划任务执行日志保存路径
默认以 脚本名.log 的方式存储
log_path="/var/log/queue/"
守护进程 PID 路径
pid_path="/var/run/queued.pid"
守护进程在启动退出时的提示名称
prog="Queued"
Start the service
start() { echo -n $"Starting $prog: "
if [ -f $pid_path ]; then
echo -n "pid "$pid_path" exists."
failure
echo
return 0
fi
if [ ! -d $log_path ]; then
mkdir -p $log_path
fi
queues=$(ls $queue_path)
for queue in $queues
do
# TODO sudo -u $php_user
nohup $php_path $queue_path$queue 1>>$log_path$queue.log 2>/dev/null &
retval=$?
if [ ! $retval -eq 0 ]; then
echo -n $queue" init failed."
failure
echo
return 0
fi
echo $! >> $pid_path
done
success
echo
return $retval
}
Stop the service
stop() { echo -n $"Stopping $prog: "
if [ ! -f $pid_path ]; then
echo -n "pid "$pid_path" not exists."
failure
echo
return 0
fi
queues=$(cat $pid_path)
for queue in $queues
do
kill -9 $queue 1>/dev/null 2>&1
retval=$?
if [ ! $retval -eq 0 ]; then
echo -n $queue" stop failed."
failure
echo
return 0
fi
done
rm -f $pid_path
success
echo
return $retval
}
main logic
case "$1" in start) start ;; stop) stop ;; restart) stop start ;; *) echo $"Usage: $0 {start|stop|restart}" exit 1 esac
exit 0 使用方法 1.根据实际情况,按照上面的配置提示,修改相应配置,并保存为 /etc/init.d/queued(建议以这样的方式命名,注意路径必须是 /etc/init.d/) 2.在 Shell 里面执行:
为守护进程脚本增加执行权限
chmod +x /etc/init.d/queued
设置开机启动
chkconfig queued on守护进程设置完成。
3.在上面配置的目录中添加测试 PHP 计划任务脚本,如 hello.php: