本文整理了Java中io.netty.util.Timer.newTimeout()
方法的一些代码示例,展示了Timer.newTimeout()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Timer.newTimeout()
方法的具体详情如下:
包路径:io.netty.util.Timer
类名称:Timer
方法名:newTimeout
[英]Schedules the specified TimerTask for one-time execution after the specified delay.
[中]将指定的TimerTask安排为在指定延迟后一次性执行。
代码示例来源:origin: AsyncHttpClient/async-http-client
private void scheduleNewIdleChannelDetector(TimerTask task) {
nettyTimer.newTimeout(task, cleanerPeriod, TimeUnit.MILLISECONDS);
}
代码示例来源:origin: mpusher/mpush
private void startHeartBeat(final int heartbeat) throws Exception {
HASHED_WHEEL_TIMER.newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
if (connection.isConnected() && healthCheck()) {
HASHED_WHEEL_TIMER.newTimeout(this, heartbeat, TimeUnit.MILLISECONDS);
}
}
}, heartbeat, TimeUnit.MILLISECONDS);
}
代码示例来源:origin: AsyncHttpClient/async-http-client
private Timeout newTimeout(TimerTask task, long delay) {
return requestSender.isClosed() ? null : nettyTimer.newTimeout(task, delay, TimeUnit.MILLISECONDS);
}
}
代码示例来源:origin: mpusher/mpush
@Override
public void run(Timeout timeout) throws Exception {
if (connection.isConnected() && healthCheck()) {
HASHED_WHEEL_TIMER.newTimeout(this, heartbeat, TimeUnit.MILLISECONDS);
}
}
}, heartbeat, TimeUnit.MILLISECONDS);
代码示例来源:origin: apache/pulsar
timeout = client.timer().newTimeout(new TimerTask() {
@Override
public void run(Timeout t) throws Exception {
代码示例来源:origin: apache/pulsar
@Override
public void run(Timeout t) throws Exception {
Set<MessageId> messageIds = new HashSet<>();
writeLock.lock();
try {
timePartitions.addLast(new ConcurrentOpenHashSet<>());
ConcurrentOpenHashSet<MessageId> headPartition = timePartitions.removeFirst();
if (!headPartition.isEmpty()) {
log.warn("[{}] {} messages have timed-out", consumerBase, timePartitions.size());
headPartition.forEach(messageId -> {
messageIds.add(messageId);
messageIdPartitionMap.remove(messageId);
});
}
} finally {
writeLock.unlock();
}
if (messageIds.size() > 0) {
consumerBase.redeliverUnacknowledgedMessages(messageIds);
}
timeout = client.timer().newTimeout(this, tickDurationInMs, TimeUnit.MILLISECONDS);
}
}, this.tickDurationInMs, TimeUnit.MILLISECONDS);
代码示例来源:origin: redisson/redisson
private void reconnect(final RedisConnection connection, final int attempts){
int timeout = 2 << attempts;
if (bootstrap.config().group().isShuttingDown()) {
return;
}
try {
timer.newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
tryReconnect(connection, Math.min(BACKOFF_CAP, attempts + 1));
}
}, timeout, TimeUnit.MILLISECONDS);
} catch (IllegalStateException e) {
// skip
}
}
代码示例来源:origin: redisson/redisson
private void reconnect(final RedisConnection connection, final int attempts){
int timeout = 2 << attempts;
if (bootstrap.config().group().isShuttingDown()) {
return;
}
try {
timer.newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
tryReconnect(connection, Math.min(BACKOFF_CAP, attempts + 1));
}
}, timeout, TimeUnit.MILLISECONDS);
} catch (IllegalStateException e) {
// skip
}
}
代码示例来源:origin: redisson/redisson
protected void sendPing(final ChannelHandlerContext ctx) {
final RedisConnection connection = RedisConnection.getFrom(ctx.channel());
final RFuture<String> future = connection.async(StringCodec.INSTANCE, RedisCommands.PING);
config.getTimer().newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
CommandData<?, ?> commandData = connection.getCurrentCommand();
if ((commandData == null || !commandData.isBlockingCommand()) &&
(future.cancel(false) || !future.isSuccess())) {
ctx.channel().close();
log.debug("channel: {} closed due to PING response timeout set in {} ms", ctx.channel(), config.getPingConnectionInterval());
} else {
sendPing(ctx);
}
}
}, config.getPingConnectionInterval(), TimeUnit.MILLISECONDS);
}
代码示例来源:origin: redisson/redisson
protected void sendPing(final ChannelHandlerContext ctx) {
final RedisConnection connection = RedisConnection.getFrom(ctx.channel());
final RFuture<String> future = connection.async(StringCodec.INSTANCE, RedisCommands.PING);
config.getTimer().newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
CommandData<?, ?> commandData = connection.getCurrentCommand();
if ((commandData == null || !commandData.isBlockingCommand()) &&
(future.cancel(false) || !future.isSuccess())) {
ctx.channel().close();
log.debug("channel: {} closed due to PING response timeout set in {} ms", ctx.channel(), config.getPingConnectionInterval());
} else {
sendPing(ctx);
}
}
}, config.getPingConnectionInterval(), TimeUnit.MILLISECONDS);
}
代码示例来源:origin: fengjiachun/Jupiter
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
boolean doReconnect = isReconnectNeeded();
if (doReconnect) {
if (attempts < 12) {
attempts++;
}
long timeout = 2 << attempts;
timer.newTimeout(this, timeout, TimeUnit.MILLISECONDS);
}
logger.warn("Disconnects with {}, address: {}, reconnect: {}.", ctx.channel(), remoteAddress, doReconnect);
ctx.fireChannelInactive();
}
代码示例来源:origin: fengjiachun/Jupiter
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
boolean doReconnect = isReconnectNeeded();
if (doReconnect) {
if (attempts < 12) {
attempts++;
}
long timeout = 2 << attempts;
timer.newTimeout(this, timeout, TimeUnit.MILLISECONDS);
}
logger.warn("Disconnects with {}, address: {}, reconnect: {}.", ctx.channel(), remoteAddress, doReconnect);
ctx.fireChannelInactive();
}
代码示例来源:origin: mpusher/mpush
timer.newTimeout(context, context.readTimeout, TimeUnit.MILLISECONDS);
代码示例来源:origin: apache/pulsar
@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
client.timer().newTimeout(PatternMultiTopicsConsumerImpl.this,
Math.min(1, conf.getPatternAutoDiscoveryPeriod()), TimeUnit.MINUTES);
}
代码示例来源:origin: apache/pulsar
public PatternMultiTopicsConsumerImpl(Pattern topicsPattern,
PulsarClientImpl client,
ConsumerConfigurationData<T> conf,
ExecutorService listenerExecutor,
CompletableFuture<Consumer<T>> subscribeFuture,
Schema<T> schema, Mode subscriptionMode, ConsumerInterceptors<T> interceptors) {
super(client, conf, listenerExecutor, subscribeFuture, schema, interceptors);
this.topicsPattern = topicsPattern;
this.subscriptionMode = subscriptionMode;
if (this.namespaceName == null) {
this.namespaceName = getNameSpaceFromPattern(topicsPattern);
}
checkArgument(getNameSpaceFromPattern(topicsPattern).toString().equals(this.namespaceName.toString()));
this.topicsChangeListener = new PatternTopicsChangedListener();
recheckPatternTimeout = client.timer().newTimeout(this, Math.min(1, conf.getPatternAutoDiscoveryPeriod()), TimeUnit.MINUTES);
}
代码示例来源:origin: apache/pulsar
@Override
public void run(Timeout timeout) throws Exception {
if (timeout.isCancelled()) {
return;
}
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Batching the messages from the batch container from timer thread", topic,
producerName);
}
// semaphore acquired when message was enqueued to container
synchronized (ProducerImpl.this) {
// If it's closing/closed we need to ignore the send batch timer and not schedule next timeout.
if (getState() == State.Closing || getState() == State.Closed) {
return;
}
batchMessageAndSend();
// schedule the next batch message task
batchMessageAndSendTimeout = client.timer()
.newTimeout(this, conf.getBatchingMaxPublishDelayMicros(), TimeUnit.MICROSECONDS);
}
}
};
代码示例来源:origin: apache/pulsar
protected void reconnectLater(Throwable exception) {
CLIENT_CNX_UPDATER.set(this, null);
if (!isValidStateForReconnection()) {
log.info("[{}] [{}] Ignoring reconnection request (state: {})", state.topic, state.getHandlerName(), state.getState());
return;
}
long delayMs = backoff.next();
log.warn("[{}] [{}] Could not get connection to broker: {} -- Will try again in {} s", state.topic, state.getHandlerName(),
exception.getMessage(), delayMs / 1000.0);
state.setState(State.Connecting);
state.client.timer().newTimeout(timeout -> {
log.info("[{}] [{}] Reconnecting after connection was closed", state.topic, state.getHandlerName());
grabCnx();
}, delayMs, TimeUnit.MILLISECONDS);
}
代码示例来源:origin: apache/pulsar
protected void connectionClosed(ClientCnx cnx) {
if (CLIENT_CNX_UPDATER.compareAndSet(this, cnx, null)) {
if (!isValidStateForReconnection()) {
log.info("[{}] [{}] Ignoring reconnection request (state: {})", state.topic, state.getHandlerName(), state.getState());
return;
}
long delayMs = backoff.next();
state.setState(State.Connecting);
log.info("[{}] [{}] Closed connection {} -- Will try again in {} s", state.topic, state.getHandlerName(), cnx.channel(),
delayMs / 1000.0);
state.client.timer().newTimeout(timeout -> {
log.info("[{}] [{}] Reconnecting after timeout", state.topic, state.getHandlerName());
grabCnx();
}, delayMs, TimeUnit.MILLISECONDS);
}
}
代码示例来源:origin: lettuce-io/lettuce-core
static void pingBeforeActivate(AsyncCommand<?, ?, ?> cmd, CompletableFuture<Boolean> initializedFuture,
ChannelHandlerContext ctx, ClientResources clientResources, Duration timeout) throws Exception {
ctx.fireUserEventTriggered(new PingBeforeActivate(cmd));
Runnable timeoutGuard = () -> {
if (cmd.isDone() || initializedFuture.isDone()) {
return;
}
initializedFuture.completeExceptionally(ExceptionFactory.createTimeoutException(
"Cannot initialize channel (PING before activate)", timeout));
};
Timeout timeoutHandle = clientResources.timer().newTimeout(t -> {
if (clientResources.eventExecutorGroup().isShuttingDown()) {
timeoutGuard.run();
return;
}
clientResources.eventExecutorGroup().submit(timeoutGuard);
}, timeout.toNanos(), TimeUnit.NANOSECONDS);
cmd.whenComplete((o, throwable) -> {
timeoutHandle.cancel();
if (throwable == null) {
ctx.fireChannelActive();
initializedFuture.complete(true);
} else {
initializedFuture.completeExceptionally(throwable);
}
});
}
代码示例来源:origin: alipay/sofa-rpc
TIMEOUT_TIMER.newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
内容来源于网络,如有侵权,请联系作者删除!