任务调度

@param   string      $no     任务编号
@param   \Closure    $fun    任务函数(闭包)
@return  Time
422143
public static function call(string $no, $fun)
    {
        if (! is_callable($fun)) {
            throw new \InvalidArgumentException("定时任务定义错误：call方法接收的fun不是有效函数");
        }

        $redis_key = Base::getRedisKey($no);
        $taskInfo = Base::getTaskInfo($redis_key);
        $run_time = $taskInfo == '' ? 0 : $taskInfo['run_time'];
        $status = new Status();

        if (empty($taskInfo)) {
            $status->newTask();
            goto goto_return;
        }

        if ($taskInfo['is_running']) {
            $status->running();
            goto goto_return;
        }

        if (time() >= $run_time) {
            Base::addHandleTaskFun($redis_key, $fun);
            $status->execTask();
            goto goto_return;
        }

        goto_return:
        return new Time($redis_key, $status->status(), $run_time);
    }
737448
def timeit(func):
    
    @wraps(func)
    def wrapped_func(*args, **kwargs):
        start  = timer()
        result = func(*args, **kwargs)
        cost   = timer() - start
        logger.debug('<method: %s> finished in %2.2f sec' % (func.__name__, cost))
        return result
    return wrapped_func
457675
function Time(name, ...rest) {
    let h = (methodDescriptor)=>{
        let {key, descriptor} = methodDescriptor;

        let fn = descriptor.value;
        let timer;

        let timeStart;
        let timeEnd;
        if (console != null && typeof console.time === 'function') {
            timeStart = console.time;
            timeEnd = console.timeEnd;
        } else {
            timeStart = ()=>{
                timer = Date.now();
            };

            timeEnd = (name)=>{
                let abstime = Date.now() - timer;

                console.log(name, '：', abstime);
            };
        }

        descriptor.value = function(...args) {
            timeStart(name || key);
            let r = fn.apply(this, args);

            if (r && typeof r.then === 'function') {
                return r.then((succ)=>{
                    timeEnd(name || key);
                    return Promise.resolve(succ);
                }, (fail)=>{
                    timeEnd(name || key);
                    return Promise.reject(fail);
                });
            } else {
                timeEnd(name || key);
                return r;
            }
        };

        return {
            ...methodDescriptor,
            descriptor,
        };
    };

    if (typeof name === 'string') {
        return h;
    } else {
        let args = [name, ...rest];
        name = void(0);
        h(...args);
    }
}
1330114
function connect($host, $port, $timeout = 0.1, $nonblock = false)
    {
        //判断超时为0或负数
        if (empty($host) or empty($port) or $timeout <= 0)
        {
            $this->errCode = -10001;
            $this->errMsg = "param error";
            return false;
        }
        $this->host = $host;
        $this->port = $port;
        //创建socket
        $this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($this->sock === false)
        {
            $this->set_error();
            return false;
        }
        //设置connect超时
        $this->set_timeout($timeout, $timeout);
        $this->setopt(SO_REUSEADDR, 1);
        //非阻塞模式下connect将立即返回
        if ($nonblock)
        {
            socket_set_nonblock($this->sock);
            @socket_connect($this->sock, $this->host, $this->port);
            return true;
        }
        else
        {
            //这里的错误信息没有任何意义，所以屏蔽掉
            if (@socket_connect($this->sock, $this->host, $this->port))
            {
                $this->connected = true;
                return true;
            }
            elseif ($this->try_reconnect)
            {
                if (@socket_connect($this->sock, $this->host, $this->port))
                {
                    $this->connected = true;
                    return true;
                }
            }
        }
        $this->set_error();
        trigger_error("connect server[{$this->host}:{$this->port}] fail. Error: {$this->errMsg}[{$this->errCode}].");
        return false;
    }
734298
def time_func(func):
    
    def timed(*args, **kwargs):
        ts = time.time()
        result = func(*args, **kwargs)
        secs = time.time() - ts
        ops_ps = kwargs.get('operations', secs) / secs
        print ("finc{} took: {} {:2.4f} operations/sec={:5.2f}".format(func.__name__, seconds_to_DHMS(secs), secs, ops_ps))
        return result
    return timed
164876
function requestAnim(func) {
    var result = q.delay(currentDelay)
      .thenResolve(func)
      .then(start);
    currentDelay += delay;
    return result;
  }
986771
public function handle($request, Closure $next)
    {
        $headers = [
            'Request-Limit' => $this->ipLimit($request)->getLimit(),
            'Request-Limit-Expire-Data' => $this->ipLimit($request)->getExpireDate(),
            'Request-Already' => $this->ipLimit($request)->getLimit() - $this->ipLimit($request)->getCount()
        ];
        if ($this->ipLimit($request)->hasTooManyAttempts($request)) {
            /*return response([
                'data' => '访问次数限制!',
                'code' => 429,
                'status_code' => 429,
            ],429, $headers);*/
			return response('访问次数限制!',429, $headers);
        }
        return $next($request);
    }
915222
function getDateTime(): \Closure {
    return function($value, \Mustache_LambdaHelper $helper) {
      $args = $this->parseArguments($helper->render($value), 'value', ['format' => null]);
      return HtmlHelper::encode(\Yii::$app->formatter->asDatetime($args['value'], $args['format']));
    };
  }
1292704
function(func, wait, options) {
      var args,
          maxTimeoutId,
          result,
          stamp,
          thisArg,
          timeoutId,
          trailingCall,
          lastCalled = 0,
          maxWait = false,
          trailing = true;

      wait = Math.max(0, wait) || 0;
      if (options === true) {
        var leading = true;
        trailing = false;
      } else if ($$.is.plainObject(options)) {
        leading = options.leading;
        maxWait = 'maxWait' in options && (Math.max(wait, options.maxWait) || 0);
        trailing = 'trailing' in options ? options.trailing : trailing;
      }
      var delayed = function() {
        var remaining = wait - (+new Date() - stamp);
        if (remaining <= 0) {
          if (maxTimeoutId) {
            clearTimeout(maxTimeoutId);
          }
          var isCalled = trailingCall;
          maxTimeoutId = timeoutId = trailingCall = undefined;
          if (isCalled) {
            lastCalled = +new Date();
            result = func.apply(thisArg, args);
            if (!timeoutId && !maxTimeoutId) {
              args = thisArg = null;
            }
          }
        } else {
          timeoutId = setTimeout(delayed, remaining);
        }
      };

      var maxDelayed = function() {
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
        maxTimeoutId = timeoutId = trailingCall = undefined;
        if (trailing || (maxWait !== wait)) {
          lastCalled = +new Date();
          result = func.apply(thisArg, args);
          if (!timeoutId && !maxTimeoutId) {
            args = thisArg = null;
          }
        }
      };

      return function() {
        args = arguments;
        stamp = +new Date();
        thisArg = this;
        trailingCall = trailing && (timeoutId || !leading);

        if (maxWait === false) {
          var leadingCall = leading && !timeoutId;
        } else {
          if (!maxTimeoutId && !leading) {
            lastCalled = stamp;
          }
          var remaining = maxWait - (stamp - lastCalled),
              isCalled = remaining <= 0;

          if (isCalled) {
            if (maxTimeoutId) {
              maxTimeoutId = clearTimeout(maxTimeoutId);
            }
            lastCalled = stamp;
            result = func.apply(thisArg, args);
          }
          else if (!maxTimeoutId) {
            maxTimeoutId = setTimeout(maxDelayed, remaining);
          }
        }
        if (isCalled && timeoutId) {
          timeoutId = clearTimeout(timeoutId);
        }
        else if (!timeoutId && wait !== maxWait) {
          timeoutId = setTimeout(delayed, wait);
        }
        if (leadingCall) {
          isCalled = true;
          result = func.apply(thisArg, args);
        }
        if (isCalled && !timeoutId && !maxTimeoutId) {
          args = thisArg = null;
        }
        return result;
      };
    }
174439
public static function jsonResponse(callable $fun): callable{
        return function (Request $request, Response $response, array $args) use ($fun){
            return $response->withJson($fun($request, $response, $args));
        };
    }
459760
function first(callable $closure = null) {
        if($closure === null) {
            if(empty($this->data)) {
                return null;
            }
            
            $keys = \array_keys($this->data);
            return ($this->data[$keys[0]] ?? null);
        }
        
        foreach($this->data as $key => $val) {
            $feed = (bool) $closure($val, $key);
            if($feed) {
                return $val;
            }
        }
        
        return null;
    }
50165
public function handle($request, Closure $next)
    {
        // 获取到微信请求里包含的几项内容
        $signature = $request->input('signature');
        $timestamp = $request->input('timestamp');
        $nonce = $request->input('nonce');

        // 公众号消息校验Token
        $token = Config::get('wechat.encodingToken');

        // 加工出自己的 signature
        $our_signature = array($token, $timestamp, $nonce);
        sort($our_signature, SORT_STRING);
        $our_signature = implode($our_signature);
        $our_signature = sha1($our_signature);

        // 用自己的 signature 去跟请求里的 signature 对比
        if ($our_signature !== $signature) {
            throw new AccessDeniedHttpException('Access Denied');
        }

        return $next($request);
    }
479703
function time(): int {
        if($this->nativeHrtime) {
            if(!$this->lastTime) {
                $this->lastTime = $this->timer;
            }
            
            $time = \hrtime(true);
            $elapsed = (int) ($time - $this->lastTime);
            $this->lastTime = $time;
        } elseif($this->hrtime) {
            $this->timer->stop();
            $elapsed = (int) $this->timer->getLastElapsedTime(\HRTime\Unit::NANOSECOND);
            $this->timer->start();
        } else {
            if(!$this->lastTime) {
                $this->lastTime = $this->timer;
            }
            
            $time = \microtime(true);
            $elapsed = $time - $this->lastTime;
            
            $this->lastTime = $time;
            $elapsed = \ceil(($elapsed * 1000000000));
        }
        
        return ((int) $elapsed);
    }
397675
public static function functionDI(\Closure $function,
                                      \Closure $callback = null)
    {
        $reflection     = new \ReflectionFunction($function);
        $functionParams = $reflection->getParameters();
        $inputParams    = [];
        if ($callback !== null) {
            foreach ($functionParams as $functionParam) {
                $param = $callback($functionParam->name);
                if (!empty($param)) {
                    $inputParams[] = $param;
                }
            }
        }
        return call_user_func_array($function, $inputParams);
    }
977564
function shouldInvoke(time) {
    let timeSinceLastCall = time - lastCallTime;

    let timeSinceLastInvoke = time - lastInvokeTime;
    // 几种满足条件的情况
    return (lastCallTime === undefined ||
      (timeSinceLastCall >= wait) ||
      (timeSinceLastCall < 0) ||
      (maxing && timeSinceLastInvoke >= maxWait)); // 超过最大等待时间
  }
522096
function chain(\Closure $func, $default = null)
    {
        $i    = 0;
        $prev = $default;
        foreach ($this->getIterator() as $key => $val) {
            if ($i++ !== 0)
                $prev = $func($val, $key, $prev);
            else
                // use default value of argument of given closure
                $prev = $func($val, $key);

        }

        return $prev;
    }
1367014
private function parse_fun_var(& $str)
    {
        // 变量： 点号变量转为数组式变量  $a.b.c   =>  $a[b][c] 
        $str = preg_replace('/\$(\w+)\.(\w+)\.(\w+)\.(\w+)/is','$\\1[\'\\2\'][\'\\3\'][\'\\4\']',$str);
        $str = preg_replace('/\$(\w+)\.(\w+)\.(\w+)/is','$\\1[\'\\2\'][\'\\3\']',$str);
        $str = preg_replace('/\$(\w+)\.(\w+)/is','$\\1[\'\\2\']',$str);
        
        // 方法: {function()}}
        $str = preg_replace("/\{(\!?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:\\-\>$]*\(([^{}]*)\))\s*\}/", "<?php print_r(\\1); ?>", $str );
        
        // 方法: {function a=a1 b=b1}
        $str = \preg_replace_callback("/\{(\w+)\s+([^}]+)\}/i", array($this,'func_arr_params_callback'), $str);
        
        // 常量: {XXXX}
        $str = preg_replace ( "/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/s", "<?php print_r(\\1); ?>", $str );
        
        // 变量: {$varname[]}, {$varname}
        //$str = preg_replace("/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff\[\]\'\"]*)\}/", "<?php print_r(isset(\\1) ? \\1 : '');\?\>", $str );
        
        // 其他: {$var...} to directly output, {$var||'abd'} or {$var}
        $str = preg_replace("/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*(?:[^{}]*))\|\|\s*([^}]+)\s*\}/s", "<?php print_r(isset(\\1) && \\1 ? \\1 : \\2); ?>", $str );
        $str = preg_replace("/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*(?:[^{}]*))\}/s", "<?php print_r(isset(\\1) ? \\1 : ''); ?>", $str );

        // 转义变量，放在后边
        /*
         * $str = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\}/es", "\$this->addquote('<?php echo \\1; ?>')", $str);
         */
        $str = preg_replace_callback ("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\}/s", array($this,'addquote_callback'), $str);
        
        return $str;
    }