心跳逻辑

@return void
559251
public function ping()
    {
        $ping_data = $this->pingData ? (string)$this->pingData : null;
        $raw = false;
        if ($this->protocolAccelerate && $ping_data && $this->protocol) {
            $ping_data = $this->preEncodeForClient($ping_data);
            $raw = true;
        }
        // 遍历所有客户端连接
        foreach ($this->_clientConnections as $connection) {
            // 上次发送的心跳还没有回复次数大于限定值就断开
            if ($this->pingNotResponseLimit > 0 &&
                $connection->pingNotResponseCount >= $this->pingNotResponseLimit * 2
            ) {
                $connection->destroy();
                continue;
            }
            // $connection->pingNotResponseCount 为 -1 说明最近客户端有发来消息，则不给客户端发送心跳
            $connection->pingNotResponseCount++;
            if ($ping_data) {
                if ($connection->pingNotResponseCount === 0 ||
                    ($this->pingNotResponseLimit > 0 && $connection->pingNotResponseCount % 2 === 1)
                ) {
                    continue;
                }
                $connection->send($ping_data, $raw);
            }
        }
    }
1073651
public function init()
    {
        // Build up the complete path to the heartbeat file
        $this->heartbeatFile = APPSERVER_BP . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
            'run' . DIRECTORY_SEPARATOR . self::HEARTBEAT_FILE_NAME;

        // Init the parent as well, as we have to get some mappings
        parent::init();
    }
62128
public function apply()
    {
        Schema::create('password_resets', function (Blueprint $table) {
            /** @noinspection PhpUndefinedMethodInspection */
            $table->string('email')->index();
            /** @noinspection PhpUndefinedMethodInspection */
            $table->string('token')->index();
            $table->timestamp('created_at');
        });
    }
407015
public function handle(): void
    {
        // Update slug for specific category
        if ($this->category) {
            $this->setCategoryFullSlug($this->category);
            return;
        }

        // Regenerate full slug for all categories
        $categories = Category::root()->get();

        $categories->each(function (Category $category) {
            $this->setCategoryFullSlug($category);
        });
    }
243143
public function up()
    {
        Schema::create('orders', function(Blueprint $table)
        {
            $table->bigIncrements('id')->comment('主键id');
            $table->string('order_no')->comment('订单号')->index();
            $table->string('order_desc')->comment('订单描述');
            $table->tinyInteger('state')->default(0)->comment('订单状态');
            $table->tinyInteger('order_type')->default(0)->comment('0 保内 1 保外');
            $table->tinyInteger('biz_type')->default(0)->comment('0 安装 1 维修');
            $table->bigInteger('merchant_id')->comment('商家id');
            $table->string('merchant_name',64)->comment('商家名称');
            $table->string('merchant_tel', 12)->comment('商家电话');
            $table->bigInteger('user_id')->comment('用户id');
            $table->string('user_name',255)->comment('用户姓名');
            $table->string('user_mobile', 12)->comment('用户电话');
            $table->decimal('user_lat')->comment('纬度');
            $table->decimal('user_lng')->comment('经度');
            $table->string('full_address')->comment('地址');
            $table->geometry('geom',4326)->comment('位置geom');
            $table->timestamp('published_at')->comment('发布工单时间');
            $table->string('big_cat')->default('')->comment('大类');
            $table->string('middle_cat')->default('')->comment('中类');
            $table->string('small_cat')->default('')->comment('小类');
            $table->timestamps();
        });
    }
673124
public function run()
    {
        // 初始化
        reset($this->queue);
        for ($i = 0; $i < $this->max; $i++) {
            if ($this->makeTask() == -1) {
                break;
            }
        }
        // 处理任务队列
        reset($this->tasks);
        while (count($this->tasks) > 0) {
            $task = current($this->tasks);
            $this->processTask($task);
            if ($task['status'] == -1 || $task['status'] == 2) {
                if ($this->saveSuccess) {
                    $this->success[] = $task;
                }
                unset($this->tasks[key($this->tasks)]);
                $this->makeTask();
            } else {
                $this->tasks[key($this->tasks)] = $task;
            }
            if (!next($this->tasks)) {
                reset($this->tasks);
            }
        }
        return $this->getSuccessInfo();
    }
904178
protected function heartbeat()
    {
        // Update the heartbeat
        $last = Cache::get($this->HEARTBEAT_CRON_KEY);
        if (empty($last->interval)) {
            $interval = 'calculating';
        } else {
            $interval = time() - $last->time;
        }

        Cache::forever($this->HEARTBEAT_CRON_KEY, (object) [
            'time' => time(),
            'interval' => $interval,
        ]);

        // The worker has died
        if (!$this->isRunning()) {

            // Log an error that the worker stopped
            $this->addLogging();
            $this->error('The '.$this->name.' worker has stopped');

            // Do work (since the worker has stopped)
            $this->fire();

        // The worker appears to be fine
        } else {
            $this->info('The '.$this->name.' worker is running');
        }
    }
1135144
public function run()
    {
       
        $this->outVerbose("Connecting...");
        if ($this->connect($this->options['user'], $this->options['password'])){
            $this->outVerbose("Connected to TAO API.");
            
            switch ($this->options['action']){
                case 'setConfig':
                    $this->setCurrentAction($this->options['action']);
                    $this->actionSetConfig();
                break;
                
                case 'install':
                    $this->setCurrentAction($this->options['action']);
                    $this->actionInstall();
                break;
            }
            
            $this->disconnect();    
        }
        else{
            $this->error("Could not connect to TAO API. Please check your user name and password.", true);
        }
       
    }
942548
public function keepAlive()
        {
            while (is_resource($this->fd)) {
                if ($this->session['heartbeat_timeout'] > 0 && $this->session['heartbeat_timeout'] + $this->heartbeatStamp - 5 < time()) {
                    $this->send(self::TYPE_HEARTBEAT);
                    $this->heartbeatStamp = time();
                }

                $r = array($this->fd);
                $w = $e = null;

                if (stream_select($r, $w, $e, 5) == 0) {
                    continue;
                }

                $res    = $this->read();
                $sess   = explode(':', $res);

                if ((int) Arrays::first($sess) === self::TYPE_EVENT) {
                    unset(Arrays::first($sess), $sess[1], $sess[2]);

                    $response = json_decode(implode(':', $sess), true);
                    $name = $response['name'];
                    $data = Arrays::first($response['args']);

                    $this->stdout('debug', 'Receive event "' . $name . '" with data "' . $data . '"');

                    if (!empty($this->callbacks[$name])) {
                        foreach ($this->callbacks[$name] as $callback) {
                            call_user_func($callback, $data);
                        }
                    }
                }
            }
        }
80270
public function run()
    {
        $superAdminUser = User::firstOrNew(['name' => 'admin']);
        $superAdminUser->email = 'admin@email.com';
        $superAdminUser->password = '123456';
        $superAdminUser->save();

        $superAdminRole = \Modules\User\Models\Role::firstOrNew(['name' => 'super-admin']);
        $superAdminRole->label = '超级管理员';
        $superAdminRole->save();
        if (!$superAdminUser->hasRole($superAdminRole)) {
            $superAdminUser->assignRole($superAdminRole);
        }

        $permissions = \Modules\User\Models\Permission::all();
        $superAdminRole->syncPermissions($permissions);

        $ordinaryRole = \Modules\User\Models\Role::firstOrNew(['name' => 'ordinary-user']);
        $ordinaryRole->label = '普通用户';
        $ordinaryRole->save();

        $ordinaryRole->syncPermissions([
            'Permission@index',
            'Permission@show',
            'Role@index',
            'Role@show',
            'Upload@index',
            'Upload@show',
            'User@index',
            'User@show'
        ]);
    }
566996
public function fire()
    {
        $this->call('migrate', array('--env' => $this->option('env'), '--package' => 'cartalyst/sentry' ) );
        $this->call('migrate', array('--env' => $this->option('env'), '--package' => 'stevemo/cpanel' ) );
        $this->call('config:publish', array('package' => 'cartalyst/sentry' ) );
        $this->call('config:publish', array('package' => 'anahkiasen/former' ) );
        $this->call('config:publish', array('package' => 'stevemo/cpanel' ) );
        $this->call('asset:publish', array('package' => 'stevemo/cpanel' ) );

        if ($this->confirm('Do you wish to create a user? [yes|no]'))
        {
            $this->call('cpanel:user');
        }
    }
225807
public function fire()
    {
        $this->call('component:migrate-reset', [
            'component'  => $this->getComponentName(),
            '--database' => $this->option('database'),
            '--force'    => $this->option('force'),
        ]);

        $this->call('component:migrate', [
            'component'  => $this->getComponentName(),
            '--database' => $this->option('database'),
            '--force'    => $this->option('force'),
        ]);

        if ($this->option('seed')) {
            $this->call('component:seed', [
                'component' => $this->getComponentName(),
            ]);
        }
    }
429831
public function init()
    {
        /**
         * 设置默认时区
         */
        if ($this->timezone)
        {
            date_default_timezone_set($this->timezone);
        }

        /**
         * 设置地区信息（地域信息）
         */
        if ($this->locale)
        {
            setlocale(LC_ALL, $this->locale);
        }

        if ($this->charset && function_exists('mb_internal_encoding'))
        {
            mb_internal_encoding($this->charset);
        }

        /**
         * 当输入字符的编码是无效的，或者字符代码不存在于输出的字符编码中时，可以为其指定一个替代字符。
         *
         * @link http://www.php.net/manual/function.mb-substitute-character.php
         */
        mb_substitute_character('none');

        // 确保输入的数据安全
        $_GET = Security::sanitize($_GET);
        $_POST = Security::sanitize($_POST);
        $_COOKIE = Security::sanitize($_COOKIE);

        self::cleanComponents();
    }
978669
public function up()
    {
        Schema::create('z_settings', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->comment('内部编号');
            $table->json('value')->comment('取值');
            $table->integer('settable_id')->nullable()->comment('可配置对象ID');
            $table->string('settable_type')->nullable()->comment('可配置对象类型');
            $table->timestamps();

            $table->index(['name', 'settable_id', 'settable_type']);
        });
    }
881439
public function handle()
    {
        $prefix = trim($this->option('prefix'));
        $max = trim($this->option('max'));
        $next = trim($this->option('next'));

        /**
         * @var Client
         */
        $client = $this->mns;
        if (!$client) {
            $this->error('请先配置阿里云MSN服务，并在DI里面注册');

            return;
        }

        $request = new ListQueueRequest($max, $prefix, $next);
        try {
            $data = [];
            $res = $client->listQueue($request);
            if ($res->isSucceed()) {
                foreach ($res->getQueueNames() as $queueName) {
                    $queue['name'] = $queueName;
                    $queueRef = $client->getQueueRef($queueName);
                    $attr = $queueRef->getAttribute()->getQueueAttributes();

                    $queue['maxSize'] = $attr->getMaximumMessageSize();
                    $queue['ttl'] = $attr->getMessageRetentionPeriod();
                    $queue['poolWait'] = $attr->getPollingWaitSeconds();
                    $queue['VisibilityTimeout'] = $attr->getVisibilityTimeout();
                    $queue['delay'] = $attr->getDelaySeconds();
                    $queue['activeMessages'] = $attr->getActiveMessages();
                    $queue['inactiveMessages'] = $attr->getInactiveMessages();
                    $queue['delayMessages'] = $attr->getDelayMessages();
                    $queue['createTime'] = date('Y-m-d H:i:s', $attr->getCreateTime());
                    $queue['updateTime'] = date('Y-m-d H:i:s', $attr->getLastModifyTime());
                    $queue['loggingEnabled'] = $attr->getLoggingEnabled() ? 'Y' : 'N';
                    $data[] = $queue;
                }
            }
            $queueHeaders = ['Name', 'MaxSize', 'TTL', 'PoolWait', 'VisibilityTimeout', 'DelaySeconds', 'Active', 'Inactive', 'Delayed', 'CreateTime', 'UpdateTime', 'EnableLog'];
            $this->line('List of Queues:');
            $this->table($queueHeaders, $data);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }
659589
public function start() {
        if ($this->dialect) {
            //允许事务嵌套
            $this->transLevel += 1;
            $dialect          = $this->dialect;
            if ($dialect->inTransaction()) {
                return true;
            }
            $rst = $dialect->beginTransaction();
            if ($rst) {
                return true;
            } else {
                $this->transLevel -= 1;
            }
        }

        return false;
    }
1358735
public function fire()
	{
		if ( ! $this->confirmToProceed()) return;

		$files = new Filesystem;

		$files->deleteDirectory(app_path('Services'));
		$files->delete(base_path('resources/views/app.blade.php'));
		$files->delete(base_path('resources/views/home.blade.php'));
		$files->deleteDirectory(app_path('Http/Controllers/Auth'));
		$files->deleteDirectory(base_path('resources/views/auth'));
		$files->deleteDirectory(base_path('resources/views/emails'));
		$files->delete(app_path('Http/Controllers/HomeController.php'));

		$files->deleteDirectory(base_path('public/css'));
		$files->deleteDirectory(base_path('public/fonts'));
		$files->put(base_path('resources/assets/less/app.less'), ''.PHP_EOL);
		$files->deleteDirectory(base_path('resources/assets/less/bootstrap'));

		$files->delete(base_path('database/migrations/2014_10_12_000000_create_users_table.php'));
		$files->delete(base_path('database/migrations/2014_10_12_100000_create_password_resets_table.php'));

		$files->put(app_path('Http/routes.php'), $files->get(__DIR__.'/stubs/fresh-routes.stub'));
		$files->put(app_path('Providers/AppServiceProvider.php'), $files->get(__DIR__.'/stubs/fresh-app-provider.stub'));

		$this->info('Scaffolding removed! Enjoy your fresh start.');
	}