这篇文章主要介绍了关于php--swoole之简单定时器使用 ,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
创建文件 sw.php
<?php
/**
* 单例操作数据库 写入
*/
class sw
{
private $_db = null;
private static $_instance;
//静态配置可拉出 设置成静态文件 或者常量
public function __construct(){
$this->_db = mysql_connect('192.168.2.130', 'root', '123456');//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('sakila')){
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('asia/shanghai');
/**
* swoole 定时器类
*/
require_once 'sw.php';
class timer
{
private static $_sw = null;
public function __construct() {
if(!isset($this->_sw)){
$this->_sw = new swoole_server('192.168.2.130', 9501);
}
}
public function run(){
$this->_sw->on('workerstart', array($this, 'onstart'));
$this->_sw->on('receive', array($this, 'onreceive'));
$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 '1';
}
}
$timer = new timer();
$timer->run();
执行方式: 放入你的linux系统中
我的存放目录是根目录下:ydy/swoole
编辑shell文件,创建fsw.sh
#!/bin/sh
pid=`ps -ef | grep '/ydy/swoole/timer.php' | grep -v grep |awk '{print $2}'`
if [ "${pid}" = "" ]
then
php /ydy/swoole/timer.php &
fi
并结合linux crontab监听脚本。
以上就是简易的php和swoole没秒写入数据库例子。
相关推荐:
如何用swoole与websocket开发一个聊天室
php加swoole加mysql 仿webqq及时聊天
利用php +swoole如何实现异步任务队列
以上就是php--swoole之简单定时器使用 的详细内容。