本文整理汇总了Java中io.netty.util.concurrent.ScheduledFuture类的典型用法代码示例。如果您正苦于以下问题:Java ScheduledFuture类的具体用法?Java ScheduledFuture怎么用?Java ScheduledFuture使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ScheduledFuture类属于io.netty.util.concurrent包,在下文中一共展示了ScheduledFuture类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doChannelRead_cancels_timeout_check_if_response_finishes_before_timeout_check_occurs
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
@Test
public void doChannelRead_cancels_timeout_check_if_response_finishes_before_timeout_check_occurs() throws Exception {
// given
ScheduledFuture timeoutCheckMock = mock(ScheduledFuture.class);
doReturn(timeoutCheckMock).when(eventLoopMock).schedule(any(Runnable.class), any(Long.class), any(TimeUnit.class));
handlerSpy.doChannelRead(ctxMock, msg);
ArgumentCaptor<BiConsumer> timeoutCheckCancellationLogicArgumentCaptor = ArgumentCaptor.forClass(BiConsumer.class);
// The 2nd whenComplete is for cancelling the timeout check if the response finishes before the timeout
verify(futureThatWillBeAttachedToSpy, times(2)).whenComplete(timeoutCheckCancellationLogicArgumentCaptor.capture());
BiConsumer<ResponseInfo<?>, Throwable> timeoutCheckCancellationLogic = timeoutCheckCancellationLogicArgumentCaptor.getAllValues().get(1);
// when: the timeout check scheduled future is not yet complete when the response finishes
doReturn(false).when(timeoutCheckMock).isDone();
timeoutCheckCancellationLogic.accept(mock(ResponseInfo.class), null);
// then: timeout check scheduled future should be cancelled
verify(timeoutCheckMock).cancel(false);
}
示例2: mock
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
@Test
public void doChannelRead_does_nothing_to_timeout_check_if_timeout_check_is_already_completed_when_response_completes() throws Exception {
// given
ScheduledFuture timeoutCheckMock = mock(ScheduledFuture.class);
doReturn(timeoutCheckMock).when(eventLoopMock).schedule(any(Runnable.class), any(Long.class), any(TimeUnit.class));
handlerSpy.doChannelRead(ctxMock, msg);
ArgumentCaptor<BiConsumer> timeoutCheckCancellationLogicArgumentCaptor = ArgumentCaptor.forClass(BiConsumer.class);
// The 2nd whenComplete is for cancelling the timeout check if the response finishes before the timeout
verify(futureThatWillBeAttachedToSpy, times(2)).whenComplete(timeoutCheckCancellationLogicArgumentCaptor.capture());
BiConsumer<ResponseInfo<?>, Throwable> timeoutCheckCancellationLogic = timeoutCheckCancellationLogicArgumentCaptor.getAllValues().get(1);
// when: the timeout check scheduled future is already done
doReturn(true).when(timeoutCheckMock).isDone();
timeoutCheckCancellationLogic.accept(mock(ResponseInfo.class), null);
// then: nothing should be done
verify(timeoutCheckMock).isDone();
verify(timeoutCheckMock, times(0)).cancel(any(Boolean.class));
verifyNoMoreInteractions(timeoutCheckMock);
}
示例3: limitedExecute
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
private O limitedExecute(ClientRequestContext ctx, I req) throws Exception {
final Deferred<O> deferred = defer(ctx, req);
final PendingTask currentTask = new PendingTask(ctx, req, deferred);
pendingRequests.add(currentTask);
drain();
if (!currentTask.isRun() && timeoutMillis != 0) {
// Current request was not delegated. Schedule a timeout.
final ScheduledFuture<?> timeoutFuture = ctx.eventLoop().schedule(
() -> deferred.close(ResponseTimeoutException.get()),
timeoutMillis, TimeUnit.MILLISECONDS);
currentTask.set(timeoutFuture);
}
return deferred.response();
}
示例4: close
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
@Override
public void close() {
isRunning.set(false);
for (ScheduledFuture<?> f : scheduledFutures) {
f.cancel(true);
}
// wait for scheduled futures to cancel
while (scheduledFutures.stream().anyMatch((f) -> !f.isDone())) {
Uninterruptibles.sleepUninterruptibly(250, TimeUnit.MILLISECONDS);
}
// handle remaining items in the queue
while (counter.get() > 0) {
drainMessageQ();
}
connectionPool.close();
}
示例5: udpConfirm
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
public static void udpConfirm(Session session) {
synchronized (session.getLocker()) {
if (!session.isUdpAuthenticated()) {
try {
session.getLocker().wait(5000);
} catch (InterruptedException e) {
Output.println(e.getMessage(), Level.DEBUG);
}
}
}
boolean authenticated = session.isUdpAuthenticated();
session.send(MessageBuilder.udpConfirm(authenticated));
if (!authenticated) {
session.close();
} else if (session.getUdpPingFuture() == null) {
ScheduledFuture<?> udpPingFuture = session.getChannel().eventLoop()
.scheduleAtFixedRate(new UdpPing(session), 10, 10, TimeUnit.SECONDS);
session.setUdpPingFuture(udpPingFuture);
}
}
示例6: activateTopologyRefreshIfNeeded
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
private void activateTopologyRefreshIfNeeded() {
if (getOptions() instanceof ClusterClientOptions) {
ClusterClientOptions options = (ClusterClientOptions) getOptions();
ClusterTopologyRefreshOptions topologyRefreshOptions = options.getTopologyRefreshOptions();
if (!topologyRefreshOptions.isPeriodicRefreshEnabled() || clusterTopologyRefreshActivated.get()) {
return;
}
if (clusterTopologyRefreshActivated.compareAndSet(false, true)) {
ScheduledFuture<?> scheduledFuture = genericWorkerPool.scheduleAtFixedRate(clusterTopologyRefreshScheduler,
options.getRefreshPeriod(), options.getRefreshPeriod(), options.getRefreshPeriodUnit());
clusterTopologyRefreshFuture.set(scheduledFuture);
}
}
}
示例7: shutdown
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
/**
* Shutdown this client and close all open connections. The client should be discarded after calling shutdown.
*
* @param quietPeriod the quiet period as described in the documentation
* @param timeout the maximum amount of time to wait until the executor is shutdown regardless if a task was submitted
* during the quiet period
* @param timeUnit the unit of {@code quietPeriod} and {@code timeout}
*/
@Override
public void shutdown(long quietPeriod, long timeout, TimeUnit timeUnit) {
if (clusterTopologyRefreshActivated.compareAndSet(true, false)) {
ScheduledFuture<?> scheduledFuture = clusterTopologyRefreshFuture.get();
try {
scheduledFuture.cancel(false);
clusterTopologyRefreshFuture.set(null);
} catch (Exception e) {
logger.debug("Could not unschedule Cluster topology refresh", e);
}
}
super.shutdown(quietPeriod, timeout, timeUnit);
}
示例8: createEventLoop
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
void createEventLoop() {
EventLoop realEventLoop = super.eventLoop();
if (realEventLoop == null) {
return;
}
eventLoop = mock(EventLoop.class, delegatesTo(realEventLoop));
doAnswer(
new Answer<ScheduledFuture<Void>>() {
@Override
public ScheduledFuture<Void> answer(InvocationOnMock invocation) throws Throwable {
Runnable command = (Runnable) invocation.getArguments()[0];
Long delay = (Long) invocation.getArguments()[1];
TimeUnit timeUnit = (TimeUnit) invocation.getArguments()[2];
return new FakeClockScheduledNettyFuture(eventLoop, command, delay, timeUnit);
}
}).when(eventLoop).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
}
示例9: async
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
public <T, R> RFuture<R> async(long timeout, Codec encoder, RedisCommand<T> command, Object ... params) {
final 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);
}
final ScheduledFuture<?> scheduledFuture = redisClient.getEventLoopGroup().schedule(new Runnable() {
@Override
public void run() {
RedisTimeoutException ex = new RedisTimeoutException("Command execution timeout for " + redisClient.getAddr());
promise.tryFailure(ex);
}
}, timeout, TimeUnit.MILLISECONDS);
promise.addListener(new FutureListener<R>() {
@Override
public void operationComplete(Future<R> future) throws Exception {
scheduledFuture.cancel(false);
}
});
send(new CommandData<T, R>(promise, encoder, command, params));
return promise;
}
示例10: cancelRequestTimeout
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
private void cancelRequestTimeout()
{
ScheduledFuture<?> timeout = this.timeout.get();
if (timeout != null) {
timeout.cancel(false);
}
}
示例11: handleConnect
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
private void handleConnect(ChannelHandlerContext ctx, HttpRequest req) {
boolean isConnected = false;
String sessionId = HttpSessionStore.getClientSessionId(req);
HttpChannelEntity httpChannelEntity = null;
if (!HttpSessionStore.checkJSessionId(sessionId)) {
sessionId = HttpSessionStore.genJSessionId();
httpChannelEntity = new HttpJsonpChannelEntity(sessionId, true);
MemoryMetaPool.registerClienId(sessionId, httpChannelEntity);
} else {
isConnected = true;
httpChannelEntity = (HttpChannelEntity) MemoryMetaPool
.getChannelEntryByClientId(sessionId);
}
Map<String, Object> map = new HashMap<String, Object>(2);
map.put("status", true);
map.put("clientId", sessionId);
String result = gson.toJson(map);
ByteBuf content = ctx.alloc().directBuffer()
.writeBytes(result.getBytes());
FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK,
content);
if (isConnected) {
res.headers().add("Set-Cookie",
ServerCookieEncoder.encode("JSESSIONID", sessionId));
}
res.headers().set(CONTENT_TYPE, HEADER_CONTENT_TYPE);
setContentLength(res, content.readableBytes());
ScheduledFuture<?> scheduleTask = ctx.executor().schedule(
new SessionTimeoutTask(sessionId), 60, TimeUnit.SECONDS);
httpChannelEntity.setScheduleTask(scheduleTask);
sendHttpResponse(ctx, req, res);
}
示例12: doChannelActive
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
@Override
public PipelineContinuationBehavior doChannelActive(ChannelHandlerContext ctx) throws Exception {
// New channel opening. See if we have too many open channels.
int actualOpenChannelsCount = openChannelsGroup.size();
if (actualOpenChannelsCount >= maxOpenChannelsThreshold) {
Channel channel = ctx.channel();
// Mark this channel as needing to be closed.
ctx.channel().attr(TOO_MANY_OPEN_CONNECTIONS_THIS_CHANNEL_SHOULD_CLOSE).set(actualOpenChannelsCount);
// Schedule a double-check event to make sure the channel gets closed.
ScheduledFuture doubleCheckScheduledFuture = ctx.channel().eventLoop().schedule(() -> {
if (channel.isOpen())
channel.close();
}, 100, TimeUnit.MILLISECONDS);
// Add a channel close future listener to cancel the double-check scheduled event immediately if the channel
// is closed quickly. Even though the double-check event will execute in 100 milliseconds that's 100
// milliseconds of potential garbage accumulating when it shouldn't. Could be a lot for a high traffic
// server (which this likely is if the open channels limit is being hit).
channel.closeFuture().addListener(future -> {
if (!doubleCheckScheduledFuture.isDone())
doubleCheckScheduledFuture.cancel(false);
});
}
else {
// Not at the threshold. Add this channel to the open channel group.
openChannelsGroup.add(ctx.channel());
}
return PipelineContinuationBehavior.CONTINUE;
}
示例13: beforeMethod
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
@Before
public void beforeMethod() {
channelMock = mock(Channel.class);
ctxMock = mock(ChannelHandlerContext.class);
tooManyOpenConnectionsAttributeMock = mock(Attribute.class);
doReturn(channelMock).when(ctxMock).channel();
doReturn(tooManyOpenConnectionsAttributeMock).when(channelMock)
.attr(TOO_MANY_OPEN_CONNECTIONS_THIS_CHANNEL_SHOULD_CLOSE);
doReturn(true).when(channelMock).isOpen();
eventLoopMock = mock(EventLoop.class);
closeFutureMock = mock(ChannelFuture.class);
doReturn(eventLoopMock).when(channelMock).eventLoop();
doReturn(closeFutureMock).when(channelMock).closeFuture();
doubleCheckScheduledFutureMock = mock(ScheduledFuture.class);
doubleCheckRunnableCaptor = ArgumentCaptor.forClass(Runnable.class);
closeFutureListenerCaptor = ArgumentCaptor.forClass(GenericFutureListener.class);
doReturn(doubleCheckScheduledFutureMock).when(eventLoopMock)
.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
doReturn(false).when(doubleCheckScheduledFutureMock).isDone();
channelGroupMock = mock(ChannelGroup.class);
maxOpenChannelsThreshold = 42;
handler = new OpenChannelLimitHandler(channelGroupMock, maxOpenChannelsThreshold);
}
示例14: scheduleAtFixedRate
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit) {
return next().scheduleAtFixedRate(command, initialDelay, period, unit);
}
示例15: scheduleWithFixedDelay
import io.netty.util.concurrent.ScheduledFuture; //导入依赖的package包/类
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit) {
return next().scheduleWithFixedDelay(command, initialDelay, delay, unit);
}