windows 服务(即,以前的 nt 服务)使您能够创建在它们自己的 windows 会话中可长时间运行的可执行应用程序 。 这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面。这使服务非常适合在服务器上使用,或任何时候,为了不影响在同一台计算 机上工作的其他用户,需要长时间运行功能时使用。还可以在不同于登录用户的特定用户帐户或默认计算机帐户的安全上下文中运行服务
简单的说就是可以长时间、自动运行在windows上的php程序。 问:这对我来说重要吗?
有什么用?
哈哈哈!有了这个,我们就可以做更多的事了。如:定期执行一个php任务、自动更新数据 ....等等。
如何实现?
必须有一台 windows服务器 或者windows pc机
必须安装得有php运行环境
必须在php 的安装目录的\ext\下有这个 php_win32service.dll文件
必须有php.ini文件里面开启 extension=php_win32service.dll 这个选项
如果你运行不起来(请看一哈上面的说明哦)最重要代码来了,如下
<?php
/**
* 利用php安装windows自动运行的服务
* $id: winservice.class.php
* $winservice = new winservice();
* $winservice->install();
*/
class winservice
{
//服务名称
var $name = 'php service';
//定义服务名称
var $info_name = "exsample php service";
//定义php.exe存放路径
var $path = "c:\\wamp\\php\\php.exe";
//定义所要执行的程序
var $params = "d:\\localhost\\service\\win32_service.php";
//定义程序分隔执行时间,单位:秒
var $sleep = 5;
private function __construct($name = '', $infoname = '', $param = '')
{
$this->name = $name;
$this->info_name = $infoname;
$this->params = $param;
}
public function install()
/* 注册服务 */
$x = win32_create_service(array(
'service' => $this->name,
'display' => $this->info_name,
'path' => $this->path,
'params' => $this->params,
));
/* 启动服务 */
win32_start_service($this->name);
if ($x !== true) {
die ('服务创建失败!');
} else {
die ('服务创建成功!');
}
public function uninstall()
/* 移除服务 */
$removeservice = win32_delete_service($this->name);
switch ($removeservice) {
case 1060:
die ('服务不存在!');
break;
case 1072:
die ('服务不能被正常移除! ');
case 0:
die ('服务已被成功移除!');
default :
die ();
public function restart()
/* 重启服务 */
$svcstatus = win32_query_service_status($this->name);
if ($svcstatus == 1060) {
echo "服务[" . $this->name . "]未被安装,请先安装";
if ($svcstatus['currentstate'] == 1) {
$s = win32_start_service($this->name);
if ($s != 0) {
echo "服务无法被启动,请重试! ";
} else {
echo "服务已启动! ";
}
} else {
$s = win32_stop_service($this->name);
echo " 服务正在执行,请重试! ";
$s = win32_start_service($this->name);
if ($s != 0) {
echo "服务无法被启动,请重试! ";
} else {
echo "服务已启动! ";
}
}
public function start()
$s = win32_start_service($this->name);
if ($s != 0) {
echo " 服务正在运行中! ";
echo " 服务已启动! ";
public function stop()
$s = win32_stop_service($this->name);
echo " 服务未启动! ";
echo " 服务已停止! ";
}
?>
win32_service.php
//检测服务是否存在
if (!win32_start_service_ctrl_dispatcher("php service")) {
die("没有发现正在运行的 [ "php service" ] 服务");
win32_set_service_status(win32_service_start_pending);
win32_set_service_status(win32_service_running);
//如果运行中
while (win32_service_control_stop != win32_get_last_control_message()) {
//写入文件
for ($i = 1; $i <= 1; $i++) {
$b_file_path = "d:\\localhost\\test.txt";
$f = fopen($b_file_path, 'a+');
$msg = 'dernier backup correctement:' . date('y/m/d h:i:s');
fwrite($f, $msg . "\r\n");
fclose($f);
sleep(1);