Esempio n. 1
1
 public function run($worker)
 {
     swoole_timer_tick(1000, function ($timer_id) {
         static $index = 0;
         $index = $index + 1;
         $this->process->push("Hello");
         var_dump($index);
         if ($index == 10) {
             swoole_timer_clear($timer_id);
         }
     });
 }
Esempio n. 2
0
 static function newAfterTimer()
 {
     $id = swoole_timer_tick(rand(1000, 10000), 'timer');
     G::$afterTimers[$id] = true;
     self::$index++;
     self::log(__METHOD__ . ": #{$id}");
 }
 private function online($who)
 {
     if (!isset($this->gens[$who])) {
         $this->gens[$who] = $this->messageGenerator($who);
         $this->sendUsers();
         $this->broadcast($who, $who . " is online.");
     }
     if ($this->timer == null) {
         $this->timer = swoole_timer_tick(3000, function () {
             try {
                 $users = $this->getAllUsers();
                 foreach ($users as $user) {
                     if (!isset($this->getMessage[$user]) && !isset($this->getUpdateUsers[$user])) {
                         if (!isset($this->maybeOffline[$user])) {
                             $this->maybeOffline[$user] = true;
                         } else {
                             $this->offline($user);
                         }
                     } else {
                         if (isset($this->maybeOffline[$user])) {
                             unset($this->maybeOffline[$user]);
                         }
                     }
                 }
             } catch (\Exception $e) {
             }
         });
     }
 }
Esempio n. 4
0
 public function onWorkerStart($serv, $worker_id)
 {
     if ($worker_id == 0) {
         $this->test = new Test();
         $this->test->index = 1;
         swoole_timer_tick(1000, array($this, 'onTick'), "Hello");
     }
 }
Esempio n. 5
0
 /**
  *  注册定时任务
  */
 protected static function register_timer()
 {
     swoole_timer_tick(60000, function ($interval) {
         Test::load_config();
     });
     swoole_timer_tick(1000, function ($interval) {
         Test::do_something($interval);
     });
 }
Esempio n. 6
0
 public static function registerTimer()
 {
     \swoole_timer_tick(60000, function ($id) {
         self::loadConfig();
         defined('PHPKIT_RUN_DEBUG') && syslog(LOG_INFO, 'reload config success');
     });
     \swoole_timer_tick(1000, function ($id) {
         self::loadTask($id);
     });
 }
Esempio n. 7
0
File: Timer.php Progetto: JeeLiu/tsf
 /**
  * [init 启动定时器]
  * @return [type] [description]
  */
 public static function init()
 {
     if (!isset(self::$tickKey)) {
         self::$tickKey = swoole_timer_tick(1000 * self::LOOPTIME, function () {
             //循环数组,踢出超时情况
             self::loop();
         });
         \SysLog::info(__METHOD__ . " init timer tick key == " . self::$tickKey, __CLASS__);
     }
 }
Esempio n. 8
0
function callback_function(swoole_process $worker)
{
    global $config;
    swoole_timer_tick($config['time'], function () {
        $fp = stream_socket_client("tcp://127.0.0.1:9502", $code, $msg, 1);
        $http_request = "GET / HTTP/1.1\r\n\r\n";
        fwrite($fp, $http_request);
        fclose($fp);
    });
}
Esempio n. 9
0
 public function addTimer()
 {
     swoole_timer_tick(10000, function ($timer_id, $params = null) {
         if ($this->is_tasking) {
             return;
         }
         $this->server->task();
         $this->is_tasking = true;
     });
 }
Esempio n. 10
0
function my_process1($process)
{
    global $argv;
    var_dump($process);
    swoole_set_process_name("php {$argv[0]}: my_process1");
    swoole_timer_tick(2000, function ($id) {
        global $serv;
        $serv->sendMessage("hello", 1);
    });
}
Esempio n. 11
0
 /**
  * [init 启动定时器]
  * @return [type] [description]
  */
 public static function init()
 {
     if (!self::$isOnTimer) {
         swoole_timer_tick(1000 * self::LOOPTIME, function ($timer_id) {
             //循环数组,踢出超时情况
             self::loop($timer_id);
             self::$isOnTimer = false;
         });
         self::$isOnTimer = true;
     }
 }
Esempio n. 12
0
 public static function init()
 {
     if (self::$timer === null) {
         for ($i = 0; $i < self::SLOT_SIZE; $i++) {
             self::$eventSlots[$i] = array();
         }
         self::$timer = swoole_timer_tick(1000 * self::LOOP_TIME, function ($tid) {
             self::loop($tid);
         });
     }
 }
Esempio n. 13
0
 /**
  * @brief 子进程做事情
  */
 public function worker()
 {
     $scheduler = $this->_objAha->getScheduler();
     swoole_timer_tick(5000, function () use($scheduler) {
         for ($i = 0; $i < 50; $i++) {
             $coroutine = $this->dbTest();
             if ($coroutine instanceof \Generator) {
                 $scheduler->newTask($coroutine);
                 $scheduler->run();
             }
         }
     });
 }
Esempio n. 14
0
File: Redo.php Progetto: eyehere/aha
 protected function _initTimer()
 {
     $redoConf = $this->_objAha->getConfig()->get('aha', 'redo');
     $interval = $redoConf['interval'];
     $triggerInterval = $redoConf['trigger_interval'];
     //当前周期内 把上个周期内失败的进行重试
     swoole_timer_tick($interval, function () {
         $this->_redo();
     });
     //每个时钟周期检查是否有redo没有发完的消息包
     swoole_timer_tick($triggerInterval, function () {
         $this->_trigger();
     });
 }
Esempio n. 15
0
 public function tick($worker)
 {
     $this->worker = $worker;
     swoole_timer_tick(500, function () {
         while (true) {
             $this->checkExit();
             $task = $this->getQueue();
             if (empty($task)) {
                 break;
             }
             $this->Run($task);
         }
     });
 }
Esempio n. 16
0
File: async.php Progetto: nosun/yaf
 public function __construct()
 {
     $fp = stream_socket_client("tcp://127.0.0.1:9504", $code, $msg, 3);
     $http_request = "GET /index.html HTTP/1.1\r\n\r\n";
     fwrite($fp, $http_request);
     swoole_event_add($fp, function ($fp) {
         echo fread($fp, 8192);
         swoole_event_del($fp);
         fclose($fp);
     });
     swoole_timer_after(2000, function () {
         echo "2000ms timeout\n";
     });
     swoole_timer_tick(1000, function () {
         echo "1000ms interval\n";
     });
 }
Esempio n. 17
0
 public function run()
 {
     $this->current_num = $this->min_worker_num;
     for ($i = 0; $i < $this->current_num; $i++) {
         $process = new swoole_process(array($this, 'task_run'), false, 2);
         $pid = $process->start();
         $this->process_list[$pid] = $process;
         $this->process_use[$pid] = 0;
     }
     foreach ($this->process_list as $process) {
         swoole_event_add($process->pipe, function ($pipe) use($process) {
             $data = $process->read();
             var_dump($data);
             $this->process_use[$data] = 0;
         });
     }
     swoole_timer_tick(1000, function ($timer_id) {
         static $index = 0;
         $index = $index + 1;
         $flag = true;
         foreach ($this->process_use as $pid => $used) {
             if ($used == 0) {
                 $flag = false;
                 $this->process_use[$pid] = 1;
                 $this->process_list[$pid]->write($index . "Hello");
                 break;
             }
         }
         if ($flag && $this->current_num < $this->max_worker_num) {
             $process = new swoole_process(array($this, 'task_run'), false, 2);
             $pid = $process->start();
             $this->process_list[$pid] = $process;
             $this->process_use[$pid] = 1;
             $this->process_list[$pid]->write($index . "Hello");
             $this->current_num++;
         }
         var_dump($index);
         if ($index == 10) {
             foreach ($this->process_list as $process) {
                 $process->write("exit");
             }
             swoole_timer_clear($timer_id);
             $this->process->exit();
         }
     });
 }
Esempio n. 18
0
 protected function memoryCheck()
 {
     $process = new \swoole_process(function (\swoole_process $worker) {
         $worker->name("kerisy-rpcserver:memoryCheck");
         swoole_timer_tick(1000, function () {
             $serverName = "kerisy-rpcserver:master";
             Reload::load($serverName, 0.8);
             //                echo date('H:i:s')."\r\n";
             if (date('H:i') == '04:00') {
                 Reload::reload($serverName);
                 //休息70s
                 sleep(70);
             }
         });
     });
     $process->start();
 }
Esempio n. 19
0
 public function work()
 {
     //是否有队列任务,有的话给worker进程发消息
     foreach ($this->workers as $pid => $worker) {
         \Log::info("队列worker{$pid}启动", [], 'tube.work');
         $data = $worker['tube'];
         if ($data) {
             $worker['process']->write($data);
         }
     }
     swoole_timer_tick(5000, function ($timerId) {
         if (!$this->pheanstalk->getConnection()->isServiceListening()) {
             //现在是一旦队列服务器崩溃的话,处理队列的主进程将退出。当然可以设置成等待,知道队列服务器恢复,只要将下列代码注释
             \Log::emergency("队列服务器崩溃了!TubeTick监听器退出", [], 'tube.tick');
             swoole_timer_clear($timerId);
             return;
         }
     });
 }
Esempio n. 20
0
 /**
  * 定时任务计时器入口文件
  * @param int    $interval  定时器时间间隔,单位秒
  * @param string $hostinfo  监听主机
  */
 public function actionRun($interval = 3, $hostinfo = '0.0.0.0:9550')
 {
     $interval = $interval * 1000;
     //单位是秒转换为基本单位毫秒
     $this->parseHostPort($hostinfo);
     echo 'timer set ', $interval, ' ms ', PHP_EOL;
     //主定时器,按interval间隔执行,单位毫秒
     swoole_timer_tick($interval, function () {
         $this->execTasks();
     });
     //如果存在额外注册定时器
     if ($this->reg_timer) {
         foreach ($this->reg_timer as $reg) {
             $tick = $reg['interval'] * 1000;
             if (method_exists($this, $reg['func'])) {
                 swoole_timer_tick($interval, [$this, $reg['func']]);
             }
         }
     }
 }
Esempio n. 21
0
 public function run()
 {
     for ($i = 0; $i < $this->worker_num; $i++) {
         $this->process_list[$i] = new swoole_process(array($this, 'task_run'), false, false);
         $this->process_list[$i]->useQueue();
         $this->process_list[$i]->start();
     }
     swoole_timer_tick(1000, function ($timer_id) {
         static $index = 0;
         $index = $index + 1;
         $this->process->push($index . "Hello");
         var_dump($index);
         if ($index == 10) {
             $this->process->push("exit");
             $this->process->push("exit");
             $this->process->push("exit");
             swoole_timer_clear($timer_id);
         }
     });
 }
Esempio n. 22
0
 public function tick(\swoole_process $worker)
 {
     $this->worker = $worker;
     defined('PHPKIT_RUN_DEBUG') && syslog(LOG_INFO, 'tick success');
     \swoole_timer_tick(500, function () {
         while (true) {
             $this->checkExit();
             $job = $this->getWaitDoingJob();
             if (!$job) {
                 defined('PHPKIT_RUN_DEBUG') && syslog(LOG_INFO, 'job is empty');
                 break;
             }
             $success = $this->run($job->getData());
             if ($success) {
                 $this->queue->delete($job);
             } else {
                 //
                 $this->queue->release($job, 1024, 300);
             }
         }
     });
 }
Esempio n. 23
0
 public function onStart()
 {
     parent::onStart();
     if ($this->server->worker_id === 0 && in_array($this->server->setting['dispatch_mode'], [1, 3])) {
         # 如果 dispatch_mode 是 1, 3 模式, 开启定期清理数据
         swoole_timer_tick(1000 * 60, function () {
             foreach (Host::$table as $key => $item) {
                 $info = $this->server->connection_info($item['fd'], $item['from_id']);
                 if ($item['removed']) {
                     if ($info) {
                         $this->server->close($item['fd'], $item['from_id']);
                     }
                     # 移除内存数据
                     Host::$table->del($key);
                 } elseif (false === $info) {
                     # 连接已经关闭
                     Host::$table->del($key);
                     # 推送服务器
                     RPC::factory($item['fd'], $item['from_id'])->trigger('server.remove', $item->group, $item->id);
                     Server::$instance->debug("remove closed client#{$item['group']}.{$item['id']}: {$item['ip']}:{$item['port']}");
                 }
             }
         });
     } else {
         swoole_timer_tick(1000 * 60, function () {
             # 清理移除掉的 server
             $time = time();
             foreach (Host::$table as $key => $item) {
                 if ($item['removed'] && $item['removed'] - $time > 10) {
                     # 清理数据
                     Host::$table->del($key);
                 }
             }
         });
     }
 }
Esempio n. 24
0
 /**
  *注册定时器
  */
 private static function registerTimerTask()
 {
     swoole_timer_tick(1000, function () {
         self::$time = time();
         try {
             self::runJob();
         } catch (Exception $e) {
             Main::log("抛出异常:" . $e->getMessage());
         }
     });
 }
Esempio n. 25
0
 */
if ($cfg && isset($cfg['debug']) && !$cfg['debug']) {
    swoole_process::daemon(1, 0);
}
/**
 * $function,子进程创建成功后要执行的函数
 * $redirect_stdin_stdout,重定向子进程的标准输入和输出。 启用此选项后,在进程内echo将不是打印屏幕,而是写入到管道。读取键盘输入将变为从管道中读取数据。 默认为阻塞读取。
 * $create_pipe,是否创建管道,启用$redirect_stdin_stdout后,此选项将忽略用户参数,强制为true 如果子进程内没有进程间通信,可以设置为false
 */
if ($cfg && isset($cfg['muti_process']) && is_array($cfg['muti_process'])) {
    foreach ($cfg['muti_process'] as $proc_cfg) {
        $process = new swoole_process(function (swoole_process $worker) use($proc_cfg) {
            swoole_timer_tick($proc_cfg['ms'], function ($timer_id) use($proc_cfg) {
                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, $proc_cfg['url']);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                $data = curl_exec($curl);
                curl_close($curl);
                logprint('info', trim($data));
            });
        }, false, false);
        $pid = $process->start();
        $workers[$pid] = $process;
    }
} else {
    logprint('warn', 'cfg is invaild');
}
master_process($workers);
function logprint($level, $msg)
{
    global $cfg;
    if ($cfg['debug'] == true) {
Esempio n. 26
0
 public function run($ip, $port = 9601)
 {
     $this->serv = $serv = new \swoole_websocket_server($ip, $port);
     //开进程事件监听的方式不可用
     /*$process = new \swoole_process(function(\swoole_process $worker) use($serv){
                 \swoole_timer_tick(1000, function () {
                     //$redis = $this->getRedis();
                     //$num = $redis->get(real_count_all);
     
                     $data = [
                         'num' => 3,
                         'time' => date('H:i:s')
                     ];
                     $cmd = json_encode($data);
                     echo $cmd . "\n";
     
                     $conn_list = $this->serv->connection_list();
                     if (!empty($conn_list)) {
                         foreach ($conn_list as $fd) {
                             $this->serv->push($fd, $cmd);
                         }
                     }
                 });
             }, true);
             $pid = $process->start();*/
     $this->serv->set(Config::get_webserver_config());
     $this->serv->on('start', function () {
         \swoole_timer_tick(1000, function () {
             $redis = $this->getRedis();
             $statistics = $redis->get('real_statistics');
             $statistics = $statistics ? json_decode($statistics, true) : ['real_statistics' => $this->redis_arr];
             $statistics['time'] = date('H:i:s');
             $cmd = json_encode($statistics);
             //初始化统计
             //$redis->set('real_statistics', json_encode($this->redis_arr));
             //echo $cmd . "\n";
             $start_fd = 0;
             while (true) {
                 $conn_list = $this->serv->connection_list($start_fd, 10);
                 if ($conn_list === false || count($conn_list) == 0) {
                     break;
                 }
                 $start_fd = end($conn_list);
                 if (!empty($conn_list)) {
                     foreach ($conn_list as $fd) {
                         //echo $cmd;
                         $this->serv->push($fd, $cmd);
                     }
                 }
             }
         });
     });
     $this->serv->on('open', function (\swoole_websocket_server $serv, $request) {
     });
     $this->serv->on('message', function (\swoole_websocket_server $serv, $frame) {
     });
     $this->serv->on('close', function ($serv, $fd) {
     });
     $this->serv->on('workerStart', function ($serv, $worker_id) {
     });
     $this->serv->start();
 }
Esempio n. 27
0
<?php

function timeout($tm)
{
    echo time() . ": Timeout #{$tm}\n";
}
$timer1 = swoole_timer_tick(1000, 'timeout', 1);
$timer2 = swoole_timer_tick(2000, 'timeout', 2);
swoole_timer_tick(3000, function ($id) {
    timeout($id);
    //swoole_timer_clear($id);
    static $remove = true;
    if ($remove) {
        global $timer1;
        swoole_timer_clear($timer1);
        swoole_timer_tick(7000, 'timeout', 7);
        $remove = false;
    }
});
$timer4 = swoole_timer_tick(4000, 'timeout', 4);
$timer5 = swoole_timer_tick(5000, 'timeout', 5);
$timer6 = swoole_timer_tick(6000, 'timeout', 6);
Esempio n. 28
0
 /**
  * 连接一个RPC服务器
  *
  * @param $ip
  * @param $port
  * @return bool
  */
 public function connect($ip, $port)
 {
     if ($this->__client) {
         @$this->__client->close();
         $this->__client = null;
     }
     /**
      * @var RPC $rpc
      */
     $this->__ip = $ip;
     $this->__port = $port;
     $this->__closeByServer = false;
     $rpc = $this->__rpc;
     $key = $rpc::_getRpcKey();
     $client = new \Swoole\Client(SWOOLE_TCP, SWOOLE_SOCK_ASYNC);
     $client->on('receive', function ($client, $data) use($key) {
         $arr = explode(Server::$EOF, $data);
         foreach ($arr as $item) {
             if ($item === '') {
                 continue;
             }
             $tmp = @msgpack_unpack($item);
             if ($key) {
                 $tmp = Server::decryption($tmp, $key);
                 if (!$tmp) {
                     \MyQEE\Server\Server::$instance->warn('rpc decryption data fail. data: ' . $item);
                     continue;
                 }
             }
             switch ($tmp->type) {
                 case 'on':
                     $event = $tmp->event;
                     if (isset($this->__events[$event])) {
                         # 回调执行
                         call_user_func_array($this->__events[$event], $tmp->args);
                     } else {
                         \MyQEE\Server\Server::$instance->warn("unknown rpc {$this->__rpc} event: {$event}");
                     }
                     break;
                 case 'close':
                     $this->__closeByServer = true;
                     $this->__client = null;
                     break;
                 default:
                     \MyQEE\Server\Server::$instance->warn("unknown rpc type {$tmp->type}");
                     break;
             }
         }
     });
     $client->on('connect', function ($client) {
         if (isset($this->__events['connect'])) {
             # 回调自定义的事件
             call_user_func($this->__events['connect'], $client);
         }
     });
     $client->on('close', function ($client) {
         $this->__client = null;
         \MyQEE\Server\Server::$instance->warn("rpc connection closed, {$this->__ip}:{$this->__port}.");
         if (!$this->isClosedByServer()) {
             # 不是被服务器强制关闭的则自动重新连接
             $this->reconnect();
         }
         if (isset($this->__events['close'])) {
             # 回调自定义的事件
             call_user_func($this->__events['close'], $client);
         }
     });
     $client->on('error', function ($client) {
         $this->__client = null;
         \MyQEE\Server\Server::$instance->warn("rpc connection({$this->__ip}:{$this->__port}) error: " . socket_strerror($client->errCode));
         # 遇到错误则自动重连
         swoole_timer_after(3000, function () {
             $this->reconnect();
         });
         if (isset($this->__events['error'])) {
             # 回调自定义的事件
             call_user_func($this->__events['error'], $client);
         }
     });
     $this->__client = $client;
     # 发心跳包
     swoole_timer_tick(1000 * 60 * 5, function () {
         if ($this->__client && $this->__client->isConnected()) {
             $this->__client->send("" . Server::$EOF);
         }
     });
     $this->__client->connect($ip, $port);
     return true;
 }
Esempio n. 29
0
<?php

//http://wiki.swoole.com/wiki/page/319.html
//四中回调http://wiki.swoole.com/wiki/page/458.html
//每隔2000ms触发一次
swoole_timer_tick(2000, function ($timer_id) {
    echo "tick-2000ms\n";
});

//3000秒后执行此函数
swoole_timer_after(3000, function () {
    echo "after 3000ms.\n";
});
Esempio n. 30
0
 protected function _initTimer()
 {
     $driveConf = $this->_objAha->getConfig()->get('aha', 'drive');
     $interval = $driveConf['interval'];
     swoole_timer_tick($interval, function () {
         $coroutine = null;
         if ($this->_bolProcessing) {
             if ($this->_bolNeedTrigger) {
                 Log::appLog()->debug(array('_bolProcessing' => true, '_bolNeedTrigger' => true));
                 $this->_bolNeedTrigger = false;
                 $coroutine = $this->_trigger();
             } else {
                 Log::appLog()->debug(array('_bolProcessing' => true, '_bolNeedTrigger' => false));
             }
         } else {
             $coroutine = $this->_taskDetect();
             Log::appLog()->debug(array('_bolProcessing' => false, '_bolNeedTrigger' => false));
         }
         if ($coroutine instanceof \Generator) {
             $this->_objScheduler->newTask($coroutine);
             $this->_objScheduler->run();
         }
     });
 }