>  기사  >  백엔드 개발  >  php--swoole 간단한 타이머 사용

php--swoole 간단한 타이머 사용

不言
不言원래의
2018-04-26 09:51:361774검색

这篇文章主要介绍了关于php--swoole之简单定时器使用 ,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下


创建文件 Sw.php

<?php 
/**
* 单例操作数据库 写入
*/
class Sw
{
    private $_db = null;
    private static $_instance;  
    //静态配置可拉出  设置成静态文件  或者常量
    public function __construct(){
        $this->_db =  mysql_connect(&#39;192.168.2.130&#39;, &#39;root&#39;, &#39;123456&#39;);//26上面数据库配置
    }
	public static function getInstance()    {    
        if(! (self::$_instance instanceof self) ) {    
            self::$_instance = new self();    
        }    
        return self::$_instance;    
    }    
  //下列函数用于调整对象的克隆行为
   private function __clone() {}
    public function insert_one(){
    	if(!mysql_select_db(&#39;sakila&#39;)){
            return false;
        }
        $time = time();
    	$sql = "INSERT INTO sw_db (add_time) VALUES (".$time.")"; 
        $result = mysql_query($sql,$this->_db);
    }
}

创建文件 Timer.php

 <?php
date_default_timezone_set(&#39;Asia/Shanghai&#39;);
/**
* swoole 定时器类
*/
require_once &#39;Sw.php&#39;;
class Timer
{
	private static $_sw = null;
	public function __construct() {
		if(!isset($this->_sw)){
			$this->_sw =  new swoole_server(&#39;192.168.2.130&#39;, 9501);
		}
	}
	public function run(){
        $this->_sw->on(&#39;WorkerStart&#39;, array($this, &#39;onStart&#39;));
        $this->_sw->on(&#39;Receive&#39;, array($this, &#39;onReceive&#39;));
        $this->_sw->start();
	}
	public function onStart(swoole_server $_sw){
	    $_sw->tick(1000, function ($id) {
	    	$this->upsert();	
       	});
	}
	private function upsert(){
		$db_sw = Sw::getInstance();
		$db_sw->insert_one();
	}
	public function onReceive(swoole_server $_sw){
		echo &#39;1&#39;;
	}
}


$timer = new Timer();
$timer->run();



执行方式: 放入你的linux系统中

我的存放目录是根目录下:ydy/swoole


编辑shell文件,创建fsw.sh

 #!/bin/sh
pid=`ps -ef | grep &#39;/ydy/swoole/Timer.php&#39; | grep -v grep |awk &#39;{print $2}&#39;`
if [ "${pid}" = "" ]
	then
	php /ydy/swoole/Timer.php &
fi

并结合linux crontab监听脚本。

以上就是简易的php和swoole没秒写入数据库例子。

相关推荐:

如何用swoole与websocket开发一个聊天室

php加swoole加mysql 仿webqq及时聊天

利用php +swoole如何实现异步任务队列

위 내용은 php--swoole 간단한 타이머 사용의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.