io.netty.util.Timeout Java Examples

The following examples show how to use io.netty.util.Timeout. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MetadataClientMock.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #2
Source File: DnsNamingService.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: Service.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #4
Source File: ElectionServiceManager.java    From hasor with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #5
Source File: UaTcpStackClient.java    From opc-ua-stack with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #6
Source File: ServerConnectionManager.java    From mpush with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #7
Source File: CipClient.java    From ethernet-ip with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: ElectionServiceManager.java    From hasor with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #9
Source File: ReadRequestTimeoutTimerTask.java    From async-gamequery-lib with MIT License 6 votes vote down vote up
@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))));
    }
}
 
Example #10
Source File: MeterStatsCollector.java    From onos with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #11
Source File: NegativeAcksTracker.java    From pulsar with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #12
Source File: IdleStateChecker.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #13
Source File: MasterSlaveConnectionManager.java    From redisson with Apache License 2.0 5 votes vote down vote up
@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;
    }
}
 
Example #14
Source File: CarreraRequest.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public void checkTimeout(Timeout timeout) {
    LOGGER.info("checkTimeout, request={}", this);
    if (finished) return;
    TimeOutHandlerMgr.getTimeOutExecutor().execute(() -> {
        timeoutHandle = null;
        if (!tryRetrySend()) {
            onFinish(ProxySendResult.FAIL_TIMEOUT);
        }
    });
}
 
Example #15
Source File: CompletableFutures.java    From Singularity with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example #16
Source File: DelayRequest.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
@Override
public void checkTimeout(Timeout timeout) {
    LOGGER.info("delay checkTimeout, request={}", this);
    if (finished) return;
    timeoutHandle = null;
    if (!tryRetrySend()) {
        onFinish(ProxySendResult.FAIL_TIMEOUT);
    }
}
 
Example #17
Source File: CipClient.java    From ethernet-ip with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #18
Source File: BaseRemoteService.java    From redisson with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #19
Source File: HashedWheelScheduler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #20
Source File: AbstractLogSyncWorker.java    From qmq with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Timeout timeout) {
    try {
        processor.processTimeout(entry);
    } catch (Exception e) {
        LOG.error("process sync request error", e);
    }
}
 
Example #21
Source File: HashedWheelTimerTest.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
	HashedWheelTimer hashedWheelTimer = new HashedWheelTimer(1000, TimeUnit.MILLISECONDS, 16);
	hashedWheelTimer.newTimeout(new TimerTask() {

		@Override
		public void run(Timeout timeout) throws Exception {
			System.out.println(System.currentTimeMillis() + "  === executed");
		}
	}, 1, TimeUnit.SECONDS);
}
 
Example #22
Source File: UaTcpStackClient.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
private void receiveResponse(UaResponseMessage response) {
    ResponseHeader header = response.getResponseHeader();
    UInteger requestHandle = header.getRequestHandle();

    CompletableFuture<UaResponseMessage> future = pending.remove(requestHandle);

    if (future != null) {
        if (header.getServiceResult().isGood()) {
            future.complete(response);
        } else {
            ServiceFault serviceFault;

            if (response instanceof ServiceFault) {
                serviceFault = (ServiceFault) response;
            } else {
                serviceFault = new ServiceFault(header);
            }

            future.completeExceptionally(new UaServiceFaultException(serviceFault));
        }

        Timeout timeout = timeouts.remove(requestHandle);
        if (timeout != null) timeout.cancel();
    } else {
        logger.warn("Received {} for unknown requestHandle: {}",
                response.getClass().getSimpleName(), requestHandle);
    }
}
 
Example #23
Source File: CompletableFutures.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public static <T> CompletableFuture<T> executeWithTimeout(
  Callable<T> callable,
  ExecutorService executorService,
  HashedWheelTimer timer,
  long timeout,
  TimeUnit timeUnit
) {
  CompletableFuture<T> future = new CompletableFuture<>();
  AtomicReference<Timeout> timeoutRef = new AtomicReference<>();
  Future<Void> underlying = executorService.submit(
    () -> {
      if (future.complete(callable.call())) {
        Timeout timeout1 = timeoutRef.get();
        if (timeout1 != null) {
          timeout1.cancel();
        }
      }
      return null;
    }
  );

  timeoutRef.set(
    timer.newTimeout(
      ignored -> {
        if (!future.isDone()) {
          if (future.completeExceptionally(new TimeoutException())) {
            underlying.cancel(true);
          }
        }
      },
      timeout,
      timeUnit
    )
  );
  return future;
}
 
Example #24
Source File: ResponseHandler.java    From NioSmtpClient with Apache License 2.0 5 votes vote down vote up
private void applyResponseTimeout(CompletableFuture<List<SmtpResponse>> responseFuture, Optional<Duration> responseTimeout, Supplier<String> debugStringSupplier) {
  responseTimeout = responseTimeout.isPresent() ? responseTimeout : defaultResponseTimeout;

  responseTimeout.ifPresent(timeout -> {
    Timeout hwtTimeout = TIMER.newTimeout(ignored -> {
      String message = String.format("[%s] Timed out waiting for a response to [%s]",
          connectionId, debugStringSupplier.get());

      responseFuture.completeExceptionally(new TimeoutException(message));
    }, timeout.toMillis(), TimeUnit.MILLISECONDS);

    responseFuture.whenComplete((ignored1, ignored2) -> hwtTimeout.cancel());
  });
}
 
Example #25
Source File: RequestContext.java    From mpush with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (tryDone()) {
        if (callback != null) {
            callback.onTimeout();
        }
    }
}
 
Example #26
Source File: ElectionServiceManager.java    From hasor with Apache License 2.0 5 votes vote down vote up
private void startCandidateTimer() {
    if (!this.candidateTimer.compareAndSet(false, true)) {
        this.logger.error("Land[Candidate] - candidateTimer -> already started");
        return;
    }
    this.logger.info("Land[Candidate] - start candidateTimer.");
    this.landContext.atTime(new TimerTask() {
        public void run(Timeout timeout) throws Exception {
            processCandidateTimer();
        }
    }, this.genTimeout());
}
 
Example #27
Source File: UaTcpClientAcknowledgeHandler.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
private Timeout startHelloTimeout(ChannelHandlerContext ctx) {
    return client.getConfig().getWheelTimer().newTimeout(
            timeout -> {
                if (!timeout.isCancelled()) {
                    handshakeFuture.completeExceptionally(
                            new UaException(StatusCodes.Bad_Timeout,
                                    "timed out waiting for acknowledge"));
                    ctx.close();
                }
            },
            5, TimeUnit.SECONDS);
}
 
Example #28
Source File: NullFlowRuleProvider.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Timeout to) throws Exception {
    for (DeviceId devId : flowTable.keySet()) {
        Set<FlowEntry> entries =
                flowTable.getOrDefault(devId, Collections.emptySet());
        providerService.pushFlowMetrics(devId, entries);
    }
    timeout = to.timer().newTimeout(to.task(), 5, TimeUnit.SECONDS);
}
 
Example #29
Source File: PingConnectionHandler.java    From redisson with Apache License 2.0 5 votes vote down vote up
private void sendPing(ChannelHandlerContext ctx) {
    RedisConnection connection = RedisConnection.getFrom(ctx.channel());
    CommandData<?, ?> commandData = connection.getCurrentCommand();
    RFuture<String> future;
    if (commandData == null || !commandData.isBlockingCommand()) {
        future = connection.async(StringCodec.INSTANCE, RedisCommands.PING);
    } else {
        future = null;
    }

    config.getTimer().newTimeout(new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (connection.isClosed()) {
                return;
            }
            if (future != null
                    && (future.cancel(false) || !future.isSuccess())) {
                ctx.channel().close();
                if (future.cause() != null) {
                    log.error("Unable to send PING command over channel: " + ctx.channel(), future.cause());
                }
                log.debug("channel: {} closed due to PING response timeout set in {} ms", ctx.channel(), config.getPingConnectionInterval());
            } else {
                sendPing(ctx);
            }
        }
    }, config.getPingConnectionInterval(), TimeUnit.MILLISECONDS);
}
 
Example #30
Source File: PatternMultiTopicsConsumerImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    CompletableFuture<Void> recheckFuture = new CompletableFuture<>();
    List<CompletableFuture<Void>> futures = Lists.newArrayListWithExpectedSize(2);

    client.getLookup().getTopicsUnderNamespace(namespaceName, subscriptionMode).thenAccept(topics -> {
        if (log.isDebugEnabled()) {
            log.debug("Get topics under namespace {}, topics.size: {}", namespaceName.toString(), topics.size());
            topics.forEach(topicName ->
                log.debug("Get topics under namespace {}, topic: {}", namespaceName.toString(), topicName));
        }

        List<String> newTopics = PulsarClientImpl.topicsPatternFilter(topics, topicsPattern);
        List<String> oldTopics = PatternMultiTopicsConsumerImpl.this.getTopics();

        futures.add(topicsChangeListener.onTopicsAdded(topicsListsMinus(newTopics, oldTopics)));
        futures.add(topicsChangeListener.onTopicsRemoved(topicsListsMinus(oldTopics, newTopics)));
        FutureUtil.waitForAll(futures)
            .thenAccept(finalFuture -> recheckFuture.complete(null))
            .exceptionally(ex -> {
                log.warn("[{}] Failed to recheck topics change: {}", topic, ex.getMessage());
                recheckFuture.completeExceptionally(ex);
                return null;
            });
    });

    // schedule the next re-check task
    this.recheckPatternTimeout = client.timer().newTimeout(PatternMultiTopicsConsumerImpl.this,
            Math.max(1, conf.getPatternAutoDiscoveryPeriod()), TimeUnit.SECONDS);
}