下面列出了io.netty.util.TimerTask#io.netty.util.Timeout 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
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);
}
@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);
}
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);
}
}
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());
}
@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();
}
@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))));
}
}
@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);
}
}
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);
}
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);
}
}
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);
}
@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);
}
}
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);
}
@Override
public void checkTimeout(Timeout timeout) {
LOGGER.info("delay checkTimeout, request={}", this);
if (finished) return;
timeoutHandle = null;
if (!tryRetrySend()) {
onFinish(ProxySendResult.FAIL_TIMEOUT);
}
}
public void checkTimeout(Timeout timeout) {
LOGGER.info("checkTimeout, request={}", this);
if (finished) return;
TimeOutHandlerMgr.getTimeOutExecutor().execute(() -> {
timeoutHandle = null;
if (!tryRetrySend()) {
onFinish(ProxySendResult.FAIL_TIMEOUT);
}
});
}
@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);
}
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);
}
});
}
private void scheduleHeartbeat() {
hTimeout = hashedWheelTimer.newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
if (!disabled) {
session.sendHeartbeat();
scheduleHeartbeat();
}
}
}, heartbeatInterval, TimeUnit.SECONDS);
}
@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);
}
}
@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);
}
@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;
}
}
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;
}
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;
}
/**
* 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;
}
}
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);
}
@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);
}
}
/**
* 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);
}
}
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;
}