Example usage for io.netty.util TimerTask TimerTask

List of usage examples for io.netty.util TimerTask TimerTask

Introduction

In this page you can find the example usage for io.netty.util TimerTask TimerTask.

Prototype

TimerTask

Source Link

Usage

From source file:org.redisson.executor.ScheduledExecutorRemoteService.java

License:Apache License

@Override
protected void awaitResultAsync(final RemoteInvocationOptions optionsCopy, final RemotePromise<Object> result,
        final RemoteServiceRequest request, final String responseName) {
    if (!optionsCopy.isResultExpected()) {
        return;/*  w  w  w.j  a  v  a2 s . c  o  m*/
    }

    Long startTime = 0L;
    if (request != null && request.getArgs() != null && request.getArgs().length > 3) {
        startTime = (Long) request.getArgs()[3];
    }
    long delay = startTime - System.currentTimeMillis();
    if (delay > 0) {
        commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                ScheduledExecutorRemoteService.super.awaitResultAsync(optionsCopy, result, request,
                        responseName);
            }
        }, delay, TimeUnit.MILLISECONDS);
    } else {
        super.awaitResultAsync(optionsCopy, result, request, responseName);
    }
}

From source file:org.redisson.executor.TasksRunnerService.java

License:Apache License

protected void scheduleRetryTimeRenewal(final String requestId) {
    ((Redisson) redisson).getConnectionManager().newTimeout(new TimerTask() {
        @Override/*w  w  w  .j av a2s .  c  o  m*/
        public void run(Timeout timeout) throws Exception {
            renewRetryTime(requestId);
        }
    }, 5, TimeUnit.SECONDS);
}

From source file:org.redisson.misc.ConnectionPool.java

License:Apache License

private void scheduleCheck(final ClientConnectionsEntry entry) {

    connectionManager.getConnectionEventsHub().fireDisconnect(entry.getClient().getAddr());

    connectionManager.newTimeout(new TimerTask() {
        @Override//from www. ja  va  2  s .  co  m
        public void run(Timeout timeout) throws Exception {
            if (entry.getFreezeReason() != FreezeReason.RECONNECT || !entry.isFreezed()) {
                return;
            }

            Future<RedisConnection> connectionFuture = entry.getClient().connectAsync();
            connectionFuture.addListener(new FutureListener<RedisConnection>() {
                @Override
                public void operationComplete(Future<RedisConnection> future) throws Exception {
                    if (entry.getFreezeReason() != FreezeReason.RECONNECT || !entry.isFreezed()) {
                        return;
                    }

                    if (!future.isSuccess()) {
                        scheduleCheck(entry);
                        return;
                    }
                    final RedisConnection c = future.getNow();
                    if (!c.isActive()) {
                        c.closeAsync();
                        scheduleCheck(entry);
                        return;
                    }

                    Future<String> f = c.asyncWithTimeout(null, RedisCommands.PING);
                    f.addListener(new FutureListener<String>() {
                        @Override
                        public void operationComplete(Future<String> future) throws Exception {
                            try {
                                if (entry.getFreezeReason() != FreezeReason.RECONNECT || !entry.isFreezed()) {
                                    return;
                                }

                                if (future.isSuccess() && "PONG".equals(future.getNow())) {
                                    entry.resetFailedAttempts();
                                    Promise<Void> promise = connectionManager.newPromise();
                                    promise.addListener(new FutureListener<Void>() {
                                        @Override
                                        public void operationComplete(Future<Void> future) throws Exception {
                                            if (entry.getNodeType() == NodeType.SLAVE) {
                                                masterSlaveEntry.slaveUp(
                                                        entry.getClient().getAddr().getHostName(),
                                                        entry.getClient().getAddr().getPort(),
                                                        FreezeReason.RECONNECT);
                                            } else {
                                                synchronized (entry) {
                                                    if (entry.getFreezeReason() == FreezeReason.RECONNECT) {
                                                        entry.setFreezed(false);
                                                        entry.setFreezeReason(null);
                                                    }
                                                }
                                            }
                                        }
                                    });
                                    initConnections(entry, promise, false);
                                } else {
                                    scheduleCheck(entry);
                                }
                            } finally {
                                c.closeAsync();
                            }
                        }
                    });
                }
            });
        }
    }, config.getReconnectionTimeout(), TimeUnit.MILLISECONDS);
}

From source file:org.redisson.pubsub.PublishSubscribeService.java

License:Apache License

private void subscribe(Codec codec, ChannelName channelName, RPromise<PubSubConnectionEntry> promise,
        PubSubType type, AsyncSemaphore lock, RedisPubSubListener<?>... listeners) {
    PubSubConnectionEntry connEntry = name2PubSubConnection.get(channelName);
    if (connEntry != null) {
        addListeners(channelName, promise, type, lock, connEntry, listeners);
        return;/*from w w w.j  ava 2  s.  c  om*/
    }

    freePubSubLock.acquire(new Runnable() {

        @Override
        public void run() {
            if (promise.isDone()) {
                lock.release();
                freePubSubLock.release();
                return;
            }

            PubSubConnectionEntry freeEntry = freePubSubConnections.peek();
            if (freeEntry == null) {
                connect(codec, channelName, promise, type, lock, listeners);
                return;
            }

            int remainFreeAmount = freeEntry.tryAcquire();
            if (remainFreeAmount == -1) {
                throw new IllegalStateException();
            }

            PubSubConnectionEntry oldEntry = name2PubSubConnection.putIfAbsent(channelName, freeEntry);
            if (oldEntry != null) {
                freeEntry.release();
                freePubSubLock.release();

                addListeners(channelName, promise, type, lock, oldEntry, listeners);
                return;
            }

            if (remainFreeAmount == 0) {
                freePubSubConnections.poll();
            }
            freePubSubLock.release();

            RFuture<Void> subscribeFuture = addListeners(channelName, promise, type, lock, freeEntry,
                    listeners);

            ChannelFuture future;
            if (PubSubType.PSUBSCRIBE == type) {
                future = freeEntry.psubscribe(codec, channelName);
            } else {
                future = freeEntry.subscribe(codec, channelName);
            }

            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        if (!promise.isDone()) {
                            subscribeFuture.cancel(false);
                        }
                        return;
                    }

                    connectionManager.newTimeout(new TimerTask() {
                        @Override
                        public void run(Timeout timeout) throws Exception {
                            subscribeFuture.cancel(false);
                        }
                    }, config.getTimeout(), TimeUnit.MILLISECONDS);
                }
            });
        }

    });
}

From source file:org.redisson.pubsub.PublishSubscribeService.java

License:Apache License

private void connect(Codec codec, ChannelName channelName, RPromise<PubSubConnectionEntry> promise,
        PubSubType type, AsyncSemaphore lock, RedisPubSubListener<?>... listeners) {
    int slot = connectionManager.calcSlot(channelName.getName());
    RFuture<RedisPubSubConnection> connFuture = nextPubSubConnection(slot);
    promise.onComplete((res, e) -> {/*from ww  w .  j  av  a  2 s .  co m*/
        if (e != null) {
            ((RPromise<RedisPubSubConnection>) connFuture).tryFailure(e);
        }
    });
    connFuture.onComplete((conn, e) -> {
        if (e != null) {
            freePubSubLock.release();
            lock.release();
            promise.tryFailure(e);
            return;
        }

        PubSubConnectionEntry entry = new PubSubConnectionEntry(conn, config.getSubscriptionsPerConnection());
        int remainFreeAmount = entry.tryAcquire();

        PubSubConnectionEntry oldEntry = name2PubSubConnection.putIfAbsent(channelName, entry);
        if (oldEntry != null) {
            releaseSubscribeConnection(slot, entry);

            freePubSubLock.release();

            addListeners(channelName, promise, type, lock, oldEntry, listeners);
            return;
        }

        if (remainFreeAmount > 0) {
            freePubSubConnections.add(entry);
        }
        freePubSubLock.release();

        RFuture<Void> subscribeFuture = addListeners(channelName, promise, type, lock, entry, listeners);

        ChannelFuture future;
        if (PubSubType.PSUBSCRIBE == type) {
            future = entry.psubscribe(codec, channelName);
        } else {
            future = entry.subscribe(codec, channelName);
        }

        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    if (!promise.isDone()) {
                        subscribeFuture.cancel(false);
                    }
                    return;
                }

                connectionManager.newTimeout(new TimerTask() {
                    @Override
                    public void run(Timeout timeout) throws Exception {
                        subscribeFuture.cancel(false);
                    }
                }, config.getTimeout(), TimeUnit.MILLISECONDS);
            }
        });
    });
}

From source file:org.redisson.pubsub.PublishSubscribeService.java

License:Apache License

public RFuture<Void> unsubscribe(ChannelName channelName, AsyncSemaphore lock) {
    PubSubConnectionEntry entry = name2PubSubConnection.remove(channelName);
    if (entry == null || connectionManager.isShuttingDown()) {
        lock.release();//from  ww w.  j  av a 2s.  c om
        return RedissonPromise.newSucceededFuture(null);
    }

    AtomicBoolean executed = new AtomicBoolean();
    RedissonPromise<Void> result = new RedissonPromise<Void>();
    ChannelFuture future = entry.unsubscribe(channelName, new BaseRedisPubSubListener() {

        @Override
        public boolean onStatus(PubSubType type, CharSequence channel) {
            if (type == PubSubType.UNSUBSCRIBE && channel.equals(channelName)) {
                executed.set(true);

                if (entry.release() == 1) {
                    freePubSubConnections.add(entry);
                }

                lock.release();
                result.trySuccess(null);
                return true;
            }
            return false;
        }

    });

    future.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                return;
            }

            connectionManager.newTimeout(new TimerTask() {
                @Override
                public void run(Timeout timeout) throws Exception {
                    if (executed.get()) {
                        return;
                    }
                    entry.getConnection()
                            .onMessage(new PubSubStatusMessage(PubSubType.UNSUBSCRIBE, channelName));
                }
            }, config.getTimeout(), TimeUnit.MILLISECONDS);
        }
    });

    return result;
}

From source file:org.redisson.pubsub.PublishSubscribeService.java

License:Apache License

public RFuture<Codec> unsubscribe(ChannelName channelName, PubSubType topicType) {
    if (connectionManager.isShuttingDown()) {
        return RedissonPromise.newSucceededFuture(null);
    }/*from   w w w. j  av a 2  s .co  m*/

    RPromise<Codec> result = new RedissonPromise<>();
    AsyncSemaphore lock = getSemaphore(channelName);
    lock.acquire(new Runnable() {
        @Override
        public void run() {
            PubSubConnectionEntry entry = name2PubSubConnection.remove(channelName);
            if (entry == null) {
                lock.release();
                result.trySuccess(null);
                return;
            }

            freePubSubLock.acquire(new Runnable() {
                @Override
                public void run() {
                    freePubSubConnections.remove(entry);
                    freePubSubLock.release();

                    Codec entryCodec;
                    if (topicType == PubSubType.PUNSUBSCRIBE) {
                        entryCodec = entry.getConnection().getPatternChannels().get(channelName);
                    } else {
                        entryCodec = entry.getConnection().getChannels().get(channelName);
                    }

                    AtomicBoolean executed = new AtomicBoolean();
                    RedisPubSubListener<Object> listener = new BaseRedisPubSubListener() {

                        @Override
                        public boolean onStatus(PubSubType type, CharSequence channel) {
                            if (type == topicType && channel.equals(channelName)) {
                                executed.set(true);

                                lock.release();
                                result.trySuccess(entryCodec);
                                return true;
                            }
                            return false;
                        }

                    };

                    ChannelFuture future;
                    if (topicType == PubSubType.PUNSUBSCRIBE) {
                        future = entry.punsubscribe(channelName, listener);
                    } else {
                        future = entry.unsubscribe(channelName, listener);
                    }

                    future.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (!future.isSuccess()) {
                                return;
                            }

                            connectionManager.newTimeout(new TimerTask() {
                                @Override
                                public void run(Timeout timeout) throws Exception {
                                    if (executed.get()) {
                                        return;
                                    }
                                    entry.getConnection()
                                            .onMessage(new PubSubStatusMessage(topicType, channelName));
                                }
                            }, config.getTimeout(), TimeUnit.MILLISECONDS);
                        }
                    });
                }
            });
        }
    });

    return result;
}

From source file:org.redisson.QueueTransferTask.java

License:Apache License

private void scheduleTask(final Long startTime) {
    if (startTime == null) {
        return;/*  www.j  a va  2  s.c  o  m*/
    }

    Timeout oldTimeout = timeoutReference.get();
    if (oldTimeout != null) {
        oldTimeout.cancel();
        timeoutReference.compareAndSet(oldTimeout, null);
    }

    long delay = startTime - System.currentTimeMillis();
    if (delay > 10) {
        Timeout timeout = connectionManager.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                pushTask();
            }
        }, delay, TimeUnit.MILLISECONDS);
        timeoutReference.set(timeout);
    } else {
        pushTask();
    }
}

From source file:org.redisson.RedissonBlockingFairQueue.java

License:Apache License

@Override
public RFuture<V> pollAsync(final long timeout, final TimeUnit unit) {
    final long startTime = System.currentTimeMillis();
    final RPromise<V> promise = newPromise();

    RFuture<Long> tryAcquireFuture = tryAcquireAsync();
    tryAcquireFuture.addListener(new FutureListener<Long>() {
        @Override/*w w  w.  jav  a2  s.c  om*/
        public void operationComplete(Future<Long> future) throws Exception {
            if (!future.isSuccess()) {
                promise.tryFailure(future.cause());
                return;
            }

            Long currentTimeout = future.getNow();
            if (currentTimeout == null) {
                long spentTime = System.currentTimeMillis() - startTime;
                long remainTime = unit.toMillis(timeout) - spentTime;
                if (remainTime > 0) {
                    final RFuture<V> pollFuture = RedissonBlockingFairQueue.super.pollAsync(remainTime,
                            TimeUnit.MILLISECONDS);
                    pollFuture.addListener(new FutureListener<V>() {
                        @Override
                        public void operationComplete(Future<V> future) throws Exception {
                            if (!future.isSuccess()) {
                                promise.tryFailure(future.cause());
                                return;
                            }

                            promise.trySuccess(future.getNow());
                        }
                    });
                } else {
                    promise.trySuccess(null);
                }
            } else {
                long spentTime = System.currentTimeMillis() - startTime;
                long remainTime = unit.toMillis(timeout) - spentTime;
                remainTime = Math.min(remainTime, currentTimeout);
                if (remainTime <= 0) {
                    promise.trySuccess(null);
                    return;
                }

                final RFuture<RedissonLockEntry> subscribeFuture = subscribe();
                final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
                subscribeFuture.addListener(new FutureListener<RedissonLockEntry>() {
                    @Override
                    public void operationComplete(Future<RedissonLockEntry> future) throws Exception {
                        if (!future.isSuccess()) {
                            promise.tryFailure(future.cause());
                            return;
                        }

                        if (futureRef.get() != null) {
                            futureRef.get().cancel();
                        }

                        tryPollAsync(startTime, timeout, unit, subscribeFuture, promise);
                    }
                });
                if (!subscribeFuture.isDone()) {
                    Timeout scheduledFuture = commandExecutor.getConnectionManager()
                            .newTimeout(new TimerTask() {
                                @Override
                                public void run(Timeout timeout) throws Exception {
                                    if (!subscribeFuture.isDone()) {
                                        subscribeFuture.cancel(false);
                                        promise.trySuccess(null);
                                    }
                                }
                            }, remainTime, TimeUnit.MILLISECONDS);
                    futureRef.set(scheduledFuture);
                }
            }
        }
    });

    return promise;
}

From source file:org.redisson.RedissonBlockingFairQueue.java

License:Apache License

private void tryTakeAsync(final RFuture<RedissonLockEntry> subscribeFuture, final RPromise<V> promise) {
    if (promise.isDone()) {
        unsubscribe(subscribeFuture);/* ww w  . j  a  v  a2s . c o m*/
        return;
    }

    RFuture<Long> tryAcquireFuture = tryAcquireAsync();
    tryAcquireFuture.addListener(new FutureListener<Long>() {
        @Override
        public void operationComplete(Future<Long> future) throws Exception {
            if (!future.isSuccess()) {
                unsubscribe(subscribeFuture);
                promise.tryFailure(future.cause());
                return;
            }

            Long currentTimeout = future.getNow();
            if (currentTimeout == null) {
                final RFuture<V> pollFuture = RedissonBlockingFairQueue.super.takeAsync();
                pollFuture.addListener(new FutureListener<V>() {
                    @Override
                    public void operationComplete(Future<V> future) throws Exception {
                        unsubscribe(subscribeFuture);
                        if (!future.isSuccess()) {
                            promise.tryFailure(future.cause());
                            return;
                        }

                        promise.trySuccess(future.getNow());
                    }
                });
            } else {
                final RedissonLockEntry entry = getEntry();
                synchronized (entry) {
                    if (entry.getLatch().tryAcquire()) {
                        tryTakeAsync(subscribeFuture, promise);
                    } else {
                        final AtomicBoolean executed = new AtomicBoolean();
                        final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>();
                        final Runnable listener = new Runnable() {
                            @Override
                            public void run() {
                                executed.set(true);
                                if (futureRef.get() != null) {
                                    futureRef.get().cancel();
                                }

                                tryTakeAsync(subscribeFuture, promise);
                            }
                        };
                        entry.addListener(listener);

                        if (!executed.get()) {
                            Timeout scheduledFuture = commandExecutor.getConnectionManager()
                                    .newTimeout(new TimerTask() {
                                        @Override
                                        public void run(Timeout t) throws Exception {
                                            synchronized (entry) {
                                                if (entry.removeListener(listener)) {
                                                    tryTakeAsync(subscribeFuture, promise);
                                                }
                                            }
                                        }
                                    }, currentTimeout, TimeUnit.MILLISECONDS);
                            futureRef.set(scheduledFuture);
                        }
                    }
                }
            }
        };
    });
}