io.netty.util.TimerTask#io.netty.util.Timeout源码实例Demo

下面列出了io.netty.util.TimerTask#io.netty.util.Timeout 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hasor   文件: ElectionServiceManager.java
private void processLeaderTimer() {
    // .如果系统退出,那么结束定时器循环
    if (!this.landStatus.get()) {
        return;
    }
    // .执行 Leader 任务
    try {
        this.processLeader();
    } catch (Exception e) {
        logger.error("Land[Leader] - " + e.getMessage(), e);
    }
    // .重启定时器
    this.landContext.atTime(new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            processLeaderTimer();
        }
    }, this.leaderHeartbeat);
}
 
源代码2 项目: opc-ua-stack   文件: UaTcpStackClient.java
private void scheduleRequestTimeout(RequestHeader requestHeader) {
    UInteger requestHandle = requestHeader.getRequestHandle();

    long timeoutHint = requestHeader.getTimeoutHint() != null ?
            requestHeader.getTimeoutHint().longValue() : DEFAULT_TIMEOUT_MS;

    Timeout timeout = wheelTimer.newTimeout(t -> {
        timeouts.remove(requestHandle);
        if (!t.isCancelled()) {
            CompletableFuture<UaResponseMessage> f = pending.remove(requestHandle);
            if (f != null) {
                String message = "request timed out after " + timeoutHint + "ms";
                f.completeExceptionally(new UaException(StatusCodes.Bad_Timeout, message));
            }
        }
    }, timeoutHint, TimeUnit.MILLISECONDS);

    timeouts.put(requestHandle, timeout);
}
 
源代码3 项目: brpc-java   文件: DnsNamingService.java
@Override
public void subscribe(SubscribeInfo subscribeInfo, final NotifyListener listener) {
    namingServiceTimer.newTimeout(
            new TimerTask() {
                @Override
                public void run(Timeout timeout) throws Exception {
                    try {
                        List<ServiceInstance> currentInstances = lookup(null);
                        Collection<ServiceInstance> addList = CollectionUtils.subtract(
                                currentInstances, lastInstances);
                        Collection<ServiceInstance> deleteList = CollectionUtils.subtract(
                                lastInstances, currentInstances);
                        listener.notify(addList, deleteList);
                        lastInstances = currentInstances;
                    } catch (Exception ex) {
                        // ignore exception
                    }
                    namingServiceTimer.newTimeout(this, updateInterval, TimeUnit.MILLISECONDS);

                }
            },
            updateInterval, TimeUnit.MILLISECONDS);
}
 
源代码4 项目: web3sdk   文件: Service.java
public void asyncSendEthereumMessage(
        BcosRequest request,
        BcosResponseCallback fiscoResponseCallback,
        TransactionSucCallback transactionSucCallback) {
    this.asyncSendEthereumMessage(request, fiscoResponseCallback);
    if (request.getTimeout() > 0) {
        final TransactionSucCallback callbackInner = transactionSucCallback;
        callbackInner.setTimeout(
                timeoutHandler.newTimeout(
                        new TimerTask() {
                            @Override
                            public void run(Timeout timeout) throws Exception {
                                // 处理超时逻辑
                                callbackInner.onTimeout();
                                // timeout时清除map的数据,所以尽管后面有回包数据,也会找不到seq->callback的关系
                                seq2TransactionCallback.remove(request.getMessageID());
                            }
                        },
                        request.getTimeout(),
                        TimeUnit.MILLISECONDS));
        this.seq2TransactionCallback.put(request.getMessageID(), callbackInner);
    } else {
        this.seq2TransactionCallback.put(request.getMessageID(), transactionSucCallback);
    }
}
 
源代码5 项目: hasor   文件: ElectionServiceManager.java
private void processFollowerTimer(long lastLeaderHeartbeat) {
    // .如果系统退出,那么结束定时器循环
    if (!this.landStatus.get()) {
        return;
    }
    // .执行 Follower 任务
    try {
        this.processFollower(lastLeaderHeartbeat);
    } catch (Exception e) {
        logger.error("Land[Follower] - " + e.getMessage(), e);
    }
    // .重启定时器
    final long curLeaderHeartbeat = this.server.getLastHeartbeat();
    this.landContext.atTime(new TimerTask() {
        public void run(Timeout timeout) throws Exception {
            processFollowerTimer(curLeaderHeartbeat);
        }
    }, genTimeout());
}
 
源代码6 项目: mpush   文件: ServerConnectionManager.java
@Override
public void run(Timeout timeout) throws Exception {
    Connection connection = this.connection;

    if (connection == null || !connection.isConnected()) {
        Logs.HB.info("heartbeat timeout times={}, connection disconnected, conn={}", timeoutTimes, connection);
        return;
    }

    if (connection.isReadTimeout()) {
        if (++timeoutTimes > CC.mp.core.max_hb_timeout_times) {
            connection.close();
            Logs.HB.warn("client heartbeat timeout times={}, do close conn={}", timeoutTimes, connection);
            return;
        } else {
            Logs.HB.info("client heartbeat timeout times={}, connection={}", timeoutTimes, connection);
        }
    } else {
        timeoutTimes = 0;
    }
    startTimeout();
}
 
源代码7 项目: ethernet-ip   文件: CipClient.java
@Override
public void itemsReceived(CpfItem[] items) {
    int connectionId = ((ConnectedAddressItem) items[0]).getConnectionId();
    ByteBuf buffer = ((ConnectedDataItemResponse) items[1]).getData();

    int sequenceNumber = buffer.readShort();
    ByteBuf data = buffer.readSlice(buffer.readableBytes()).retain();

    Timeout timeout = timeouts.remove(sequenceNumber);
    if (timeout != null) timeout.cancel();

    CompletableFuture<ByteBuf> future = pending.remove(sequenceNumber);

    if (future != null) {
        future.complete(data);
    } else {
        ReferenceCountUtil.release(data);
    }

    ReferenceCountUtil.release(buffer);
}
 
@Override
public void run(Timeout timeout) throws Exception {
    log.debug("Timeout occured for Session {}", id);
    //Notify the listener that timeout has occured
    final SessionValue session = sessionManager.getSession(id);

    //Do not proceed if the session is null
    if (session == null) {
        log.error("could not find session value for id {}. Registry Size : {}", id, sessionManager.getSessionEntries().size());
        return;
    }

    //Check first if the promise has been completed
    if (session.getClientPromise() != null && !session.getClientPromise().isDone() && !session.getClientPromise().isCancelled() && !timeout.isCancelled()) {
        //Send a ReadTimeoutException to the client
        session.getClientPromise().completeExceptionally(new ReadTimeoutException(id, String.format("Timeout occured for '%s' Started: %f seconds ago", id, ((double) Duration.ofMillis(System.currentTimeMillis() - session.getTimeRegistered()).toMillis() / 1000.0))));
    }
}
 
源代码9 项目: onos   文件: MeterStatsCollector.java
@Override
public void run(Timeout timeout) throws Exception {
    if (!sw.isConnected()) {
        log.debug("Switch {} disconnected. Aborting meter stats collection", sw.getStringId());
        return;
    }

    log.trace("Collecting stats for {}", sw.getStringId());

    sendMeterStatisticRequest();

    if (!this.stopTimer) {
        log.trace("Scheduling stats collection in {} seconds for {}",
                this.refreshInterval, this.sw.getStringId());
        timeout.timer().newTimeout(this, refreshInterval,
                TimeUnit.SECONDS);
    }
}
 
源代码10 项目: pulsar   文件: NegativeAcksTracker.java
private synchronized void triggerRedelivery(Timeout t) {
    if (nackedMessages.isEmpty()) {
        this.timeout = null;
        return;
    }

    // Group all the nacked messages into one single re-delivery request
    Set<MessageId> messagesToRedeliver = new HashSet<>();
    long now = System.nanoTime();
    nackedMessages.forEach((msgId, timestamp) -> {
        if (timestamp < now) {
            addChunkedMessageIdsAndRemoveFromSequnceMap(msgId, messagesToRedeliver, this.consumer);
            messagesToRedeliver.add(msgId);
        }
    });

    messagesToRedeliver.forEach(nackedMessages::remove);
    consumer.onNegativeAcksSend(messagesToRedeliver);
    consumer.redeliverUnacknowledgedMessages(messagesToRedeliver);

    this.timeout = timer.newTimeout(this::triggerRedelivery, timerIntervalNanos, TimeUnit.NANOSECONDS);
}
 
源代码11 项目: pinpoint   文件: MetadataClientMock.java
private void scheduleNextRetry(GeneratedMessageV3 request, int remainingRetryCount) {
    final TimerTask timerTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (timeout.cancel()) {
                return;
            }
            logger.info("Retry {} {}", remainingRetryCount, request);
            request(request, remainingRetryCount - 1);
        }
    };

    try {
        retryTimer.newTimeout(timerTask, 1000, TimeUnit.MILLISECONDS);
    } catch (RejectedExecutionException e) {
        logger.debug("retry fail {}", e.getCause(), e);
    }
}
 
源代码12 项目: redisson   文件: BaseRemoteService.java
protected <T> void scheduleCheck(String mapName, RequestId requestId, RPromise<T> cancelRequest) {
    commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (cancelRequest.isDone()) {
                return;
            }

            RMap<String, T> canceledRequests = getMap(mapName);
            RFuture<T> future = canceledRequests.removeAsync(requestId.toString());
            future.onComplete((request, ex) -> {
                if (cancelRequest.isDone()) {
                    return;
                }
                if (ex != null) {
                    scheduleCheck(mapName, requestId, cancelRequest);
                    return;
                }
                
                if (request == null) {
                    scheduleCheck(mapName, requestId, cancelRequest);
                } else {
                    cancelRequest.trySuccess(request);
                }
            });
        }
    }, 3000, TimeUnit.MILLISECONDS);
}
 
源代码13 项目: onos   文件: TunnelStatsCollector.java
@Override
public void run(Timeout timeout) throws Exception {
    if (stopped || timeout.isCancelled()) {
        return;
    }
    log.trace("Collecting stats for {}", pcepTunnelId);

    sendTunnelStatistic();
    if (!stopped && !timeout.isCancelled()) {
        log.trace("Scheduling stats collection in {} seconds for {}",
                  this.refreshInterval, pcepTunnelId);
        timeout.timer().newTimeout(this, refreshInterval, TimeUnit.SECONDS);
    }

}
 
源代码14 项目: tchannel-java   文件: OutRequest.java
protected boolean shouldRetryOnError() {
    if (lastError == null) {
        return false;
    }

    String flags = request.getRetryFlags();
    if (flags.contains("n")) {
        return false;
    }

    ErrorType errorType = lastError.getErrorType();

    switch (errorType) {
        case BadRequest:
        case Cancelled:
        case Unhealthy:
            return false;

        case Busy:
        case Declined:
            return true;

        case Timeout:
            return flags.contains("t");

        case NetworkError:
        case FatalProtocolError:
        case UnexpectedError:
             return flags.contains("c");

        default:
            return false;
    }
}
 
public Timeout newTimeout(TimerTask task, long recycleDelay, TimeUnit unit,
                          BooleanSupplier checkCondition) {

    return super
        .newTimeout(new RecycleAsyncTimerTask(task, recycleDelay, unit, checkCondition),
            recycleDelay, unit);
}
 
源代码16 项目: DDMQ   文件: DelayRequest.java
@Override
public void checkTimeout(Timeout timeout) {
    LOGGER.info("delay checkTimeout, request={}", this);
    if (finished) return;
    timeoutHandle = null;
    if (!tryRetrySend()) {
        onFinish(ProxySendResult.FAIL_TIMEOUT);
    }
}
 
源代码17 项目: DDMQ   文件: CarreraRequest.java
public void checkTimeout(Timeout timeout) {
    LOGGER.info("checkTimeout, request={}", this);
    if (finished) return;
    TimeOutHandlerMgr.getTimeOutExecutor().execute(() -> {
        timeoutHandle = null;
        if (!tryRetrySend()) {
            onFinish(ProxySendResult.FAIL_TIMEOUT);
        }
    });
}
 
源代码18 项目: arcusplatform   文件: HashedWheelScheduler.java
@Override
protected ScheduledTask doSchedule(Runnable task, Date time, long delay, TimeUnit unit) {
   Timeout timo = timer.newTimeout(new TimerTask() {
      @Override
      public void run(Timeout timeout) throws Exception {
         task.run();
      }
   }, delay, unit);
   return new TimeoutScheduledTask(timo);
}
 
源代码19 项目: ffwd   文件: RetryingProtocolConnection.java
private void trySetup(final int attempt) {
    log.info("Attempt {}", action);

    final ChannelFuture connect = action.setup();

    connect.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                log.info("Successful {}", action);
                setChannel(future.channel());
                return;
            }

            final long delay = policy.delay(attempt);

            log.warn("Failed {} (attempt: {}), retrying in {}s: {}", action, attempt + 1,
                TimeUnit.SECONDS.convert(delay, TimeUnit.MILLISECONDS),
                future.cause().getMessage());

            timer.newTimeout(new TimerTask() {
                @Override
                public void run(Timeout timeout) throws Exception {
                    if (stopped.get()) {
                        return;
                    }

                    trySetup(attempt + 1);
                }
            }, delay, TimeUnit.MILLISECONDS);
        }
    });
}
 
源代码20 项目: socketio   文件: SocketIOHeartbeatScheduler.java
private void scheduleHeartbeat() {
  hTimeout = hashedWheelTimer.newTimeout(new TimerTask() {
    @Override
    public void run(Timeout timeout) throws Exception {
      if (!disabled) {
        session.sendHeartbeat();
        scheduleHeartbeat();
      }
    }
  }, heartbeatInterval, TimeUnit.SECONDS);

}
 
源代码21 项目: ftdc   文件: RecieveMessageTimerTask.java
@Override
public void run(Timeout timeout) throws Exception {
	RequestIdentity ri = ApplicationRuntime.getRequestIdentity(requestIdentity.getBrokerId(), requestIdentity.getUserId(), requestIdentity.getReqId());
	if(ri != null) {
		logger.warn("reqId {}, brokerid {}, uid {} timeouts", requestIdentity.getReqId(), requestIdentity.getBrokerId(), requestIdentity.getUserId());
		RspError recieveMessageError = RspError.buildRecieveMessageError();
		spi.onRspError(recieveMessageError, this.requestIdentity);
	}
}
 
源代码22 项目: brpc-java   文件: FileNamingService.java
@Override
public void subscribe(final SubscribeInfo subscribeInfo, final NotifyListener listener) {
    namingServiceTimer.newTimeout(
            new TimerTask() {
                @Override
                public void run(Timeout timeout) throws Exception {
                    try {
                        File file = new File(filePath);
                        long currentModified = file.lastModified();
                        if (currentModified > lastModified) {
                            List<ServiceInstance> currentInstances = lookup(subscribeInfo);
                            Collection<ServiceInstance> addList = CollectionUtils.subtract(
                                    currentInstances, lastInstances);
                            Collection<ServiceInstance> deleteList = CollectionUtils.subtract(
                                    lastInstances, currentInstances);
                            listener.notify(addList, deleteList);
                            lastInstances = currentInstances;
                        }
                    } catch (Exception ex) {
                        // ignore exception
                    }
                    namingServiceTimer.newTimeout(this, updateInterval, TimeUnit.MILLISECONDS);

                }
            },
            updateInterval, TimeUnit.MILLISECONDS);
}
 
源代码23 项目: redisson   文件: MasterSlaveConnectionManager.java
@Override
public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) {
    try {
        return timer.newTimeout(task, delay, unit);
    } catch (IllegalStateException e) {
        if (isShuttingDown()) {
            return DUMMY_TIMEOUT;
        }
        
        throw e;
    }
}
 
源代码24 项目: redisson   文件: RedisConnection.java
public <T, R> RFuture<R> async(long timeout, Codec encoder, RedisCommand<T> command, Object... params) {
    RPromise<R> promise = new RedissonPromise<R>();
    if (timeout == -1) {
        timeout = redisClient.getCommandTimeout();
    }
    
    if (redisClient.getEventLoopGroup().isShuttingDown()) {
        RedissonShutdownException cause = new RedissonShutdownException("Redisson is shutdown");
        return RedissonPromise.newFailedFuture(cause);
    }

    Timeout scheduledFuture = redisClient.getTimer().newTimeout(t -> {
        RedisTimeoutException ex = new RedisTimeoutException("Command execution timeout for command: "
                + LogHelper.toString(command, params) + ", Redis client: " + redisClient);
        promise.tryFailure(ex);
    }, timeout, TimeUnit.MILLISECONDS);
    
    promise.onComplete((res, e) -> {
        scheduledFuture.cancel();
    });
    
    ChannelFuture writeFuture = send(new CommandData<T, R>(promise, encoder, command, params));
    writeFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                promise.tryFailure(future.cause());
            }
        }
    });
    return promise;
}
 
源代码25 项目: modbus   文件: ModbusTcpMaster.java
public <T extends ModbusResponse> CompletableFuture<T> sendRequest(ModbusRequest request, int unitId) {
    CompletableFuture<T> future = new CompletableFuture<>();

    channelFsm.getChannel().whenComplete((ch, ex) -> {
        if (ch != null) {
            short txId = (short) transactionId.incrementAndGet();

            Timeout timeout = config.getWheelTimer().newTimeout(t -> {
                if (t.isCancelled()) return;

                PendingRequest<? extends ModbusResponse> timedOut = pendingRequests.remove(txId);
                if (timedOut != null) {
                    timedOut.promise.completeExceptionally(new ModbusTimeoutException(config.getTimeout()));
                    timeoutCounter.inc();
                }
            }, config.getTimeout().getSeconds(), TimeUnit.SECONDS);

            Timer.Context context = responseTimer.time();

            pendingRequests.put(txId, new PendingRequest<>(future, timeout, context));

            ch.writeAndFlush(new ModbusTcpPayload(txId, (short) unitId, request)).addListener(f -> {
                if (!f.isSuccess()) {
                    PendingRequest<?> p = pendingRequests.remove(txId);
                    if (p != null) {
                        p.promise.completeExceptionally(f.cause());
                        p.timeout.cancel();
                    }
                }
            });

            requestCounter.inc();
        } else {
            future.completeExceptionally(ex);
        }
    });

    return future;
}
 
源代码26 项目: opc-ua-stack   文件: Stack.java
/**
 * Release shared resources, waiting at most the specified timeout for the {@link NioEventLoopGroup} to shutdown
 * gracefully.
 *
 * @param timeout the duration of the timeout.
 * @param unit    the unit of the timeout duration.
 */
public static synchronized void releaseSharedResources(long timeout, TimeUnit unit) {
    if (EVENT_LOOP != null) {
        try {
            EVENT_LOOP.shutdownGracefully().await(timeout, unit);
        } catch (InterruptedException e) {
            LoggerFactory.getLogger(Stack.class)
                    .warn("Interrupted awaiting event loop shutdown.", e);
        }
        EVENT_LOOP = null;
    }

    if (SCHEDULED_EXECUTOR_SERVICE != null) {
        SCHEDULED_EXECUTOR_SERVICE.shutdown();
        SCHEDULED_EXECUTOR_SERVICE = null;
    }

    if (EXECUTOR_SERVICE != null) {
        EXECUTOR_SERVICE.shutdown();
        EXECUTOR_SERVICE = null;
    }

    if (WHEEL_TIMER != null) {
        WHEEL_TIMER.stop().forEach(Timeout::cancel);
        WHEEL_TIMER = null;
    }
}
 
源代码27 项目: hasor   文件: ElectionServiceManager.java
private void startLeaderTimer() {
    if (!this.leaderTimer.compareAndSet(false, true)) {
        this.logger.error("Land[Leader] - leaderTimer -> already started");
        return;
    }
    this.logger.info("Land[Leader] - start leaderTimer.");
    this.landContext.atTime(new TimerTask() {
        public void run(Timeout timeout) throws Exception {
            processLeaderTimer();
        }
    }, this.leaderHeartbeat);
}
 
源代码28 项目: Jupiter   文件: IdleStateChecker.java
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled() || !ctx.channel().isOpen()) {
        return;
    }

    long lastReadTime = IdleStateChecker.this.lastReadTime;
    long nextDelay = readerIdleTimeMillis;
    if (!reading) {
        nextDelay -= SystemClock.millisClock().now() - lastReadTime;
    }
    if (nextDelay <= 0) {
        // Reader is idle - set a new timeout and notify the callback.
        readerIdleTimeout = timer.newTimeout(this, readerIdleTimeMillis, TimeUnit.MILLISECONDS);
        try {
            IdleStateEvent event;
            if (firstReaderIdleEvent) {
                firstReaderIdleEvent = false;
                event = IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT;
            } else {
                event = IdleStateEvent.READER_IDLE_STATE_EVENT;
            }
            channelIdle(ctx, event);
        } catch (Throwable t) {
            ctx.fireExceptionCaught(t);
        }
    } else {
        // Read occurred before the timeout - set a new timeout with shorter delay.
        readerIdleTimeout = timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS);
    }
}
 
源代码29 项目: Singularity   文件: CompletableFutures.java
/**
 * Return a future that completes with a timeout after a delay.
 */
public static CompletableFuture<Timeout> timeoutFuture(
  HashedWheelTimer hwt,
  long delay,
  TimeUnit timeUnit
) {
  try {
    CompletableFuture<Timeout> future = new CompletableFuture<>();
    hwt.newTimeout(future::complete, delay, timeUnit);
    return future;
  } catch (Throwable t) {
    return exceptionalFuture(t);
  }
}
 
源代码30 项目: ethernet-ip   文件: CipClient.java
public CompletableFuture<ByteBuf> sendConnectedData(Consumer<ByteBuf> dataEncoder, int connectionId) {
    CompletableFuture<ByteBuf> future = new CompletableFuture<>();

    ConnectedAddressItem addressItem = new ConnectedAddressItem(connectionId);

    int sequenceNumber = nextSequenceNumber();

    ConnectedDataItemRequest dataItem = new ConnectedDataItemRequest((b) -> {
        b.writeShort(sequenceNumber);
        dataEncoder.accept(b);
    });

    CpfPacket packet = new CpfPacket(addressItem, dataItem);
    SendUnitData command = new SendUnitData(packet);

    Timeout timeout = getConfig().getWheelTimer().newTimeout(tt -> {
        if (tt.isCancelled()) return;
        CompletableFuture<ByteBuf> f = pending.remove(sequenceNumber);
        if (f != null) {
            String message = String.format(
                "sequenceNumber=%s timed out waiting %sms for response",
                sequenceNumber, getConfig().getTimeout().toMillis()
            );
            f.completeExceptionally(new TimeoutException(message));
        }
    }, getConfig().getTimeout().toMillis(), TimeUnit.MILLISECONDS);

    pending.put(sequenceNumber, future);
    timeouts.put(sequenceNumber, timeout);

    sendUnitData(command).whenComplete((v, ex) -> {
        // sendUnitData() fails fast if the channel isn't available
        if (ex != null) future.completeExceptionally(ex);
    });

    return future;
}