Example usage for io.netty.util Timeout isCancelled

List of usage examples for io.netty.util Timeout isCancelled

Introduction

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

Prototype

boolean isCancelled();

Source Link

Document

Returns true if and only if the TimerTask associated with this handle has been cancelled.

Usage

From source file:com.ibasco.agql.core.ReadRequestTimeoutTimerTask.java

License:Open Source License

@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;/* w ww. ja v a 2 s.  c  o  m*/
    }

    //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))));
    }
}

From source file:com.yahoo.pulsar.client.impl.ProducerImpl.java

License:Apache License

/**
 * Process sendTimeout events/*  w  w  w  .  j ava  2  s  . c  o  m*/
 */
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    long timeToWaitMs;

    synchronized (this) {
        OpSendMsg firstMsg = pendingMessages.peek();
        if (firstMsg == null) {
            // If there are no pending messages, reset the timeout to the configured value.
            timeToWaitMs = conf.getSendTimeoutMs();
        } else {
            // If there is at least one message, calculate the diff between the message timeout and the current
            // time.
            long diff = (firstMsg.createdAt + conf.getSendTimeoutMs()) - System.currentTimeMillis();
            if (diff <= 0) {
                // The diff is less than or equal to zero, meaning that the message has been timed out.
                // Set the callback to timeout on every message, then clear the pending queue.
                log.info("[{}] [{}] Message send timed out. Failing {} messages", topic, producerName,
                        pendingMessages.size());

                PulsarClientException te = new PulsarClientException.TimeoutException(
                        "Could not send message to broker within given timeout");
                failPendingMessages(cnx(), te);
                stats.incrementSendFailed(pendingMessages.size());
                // Since the pending queue is cleared now, set timer to expire after configured value.
                timeToWaitMs = conf.getSendTimeoutMs();
            } else {
                // The diff is greater than zero, set the timeout to the diff value
                timeToWaitMs = diff;
            }
        }
    }

    sendTimeout = client.timer().newTimeout(this, timeToWaitMs, TimeUnit.MILLISECONDS);
}

From source file:io.lettuce.core.protocol.ConnectionWatchdog.java

License:Apache License

void prepareClose() {

    setListenOnChannelInactive(false);/*from  www. j  av  a2 s.  c  om*/
    setReconnectSuspended(true);

    Timeout reconnectScheduleTimeout = this.reconnectScheduleTimeout;
    if (reconnectScheduleTimeout != null && !reconnectScheduleTimeout.isCancelled()) {
        reconnectScheduleTimeout.cancel();
    }

    reconnectionHandler.prepareClose();
}

From source file:me.schiz.jmeter.ring.tcp.TimeoutTask.java

License:Apache License

@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isExpired() && !timeout.isCancelled() && !ring.get(id).isPrepared) {
        ring.timeout(id, reason);// w ww  .  j a va2 s  . co  m
    }
}

From source file:me.schiz.jmeter.ring.udp.TimeoutTask.java

License:Apache License

@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isExpired() && !timeout.isCancelled()) {
        ring.get(id).lock.lock();//from  w w w. j  a  va2 s  .com
        log.error("Timeout token #" + id + ". Reason: " + reason);
        //ring.reset(id);
        Token t = ring.get(id);
        try {
            SampleResult sr = t.sampleResult;
            Queue queue = t.queue;
            t.sampleResult = null;
            t.queue = null;
            sr.setSuccessful(false);
            sr.setResponseCode(ERROR_502);
            sr.sampleEnd();
            while (!queue.offer(sr)) {
            }
        } catch (NullPointerException npe) {

        }
        ring.reset(id);
        ring.get(id).lock.unlock();
    }
}

From source file:org.apache.pulsar.client.impl.PatternMultiTopicsConsumerImpl.java

License:Apache License

@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;/* w  ww. j  a v  a  2 s .c  om*/
    }

    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
    recheckPatternTimeout = client.timer().newTimeout(PatternMultiTopicsConsumerImpl.this,
            Math.min(1, conf.getPatternAutoDiscoveryPeriod()), TimeUnit.MINUTES);
}

From source file:org.apache.pulsar.client.impl.PatternTopicsConsumerImpl.java

License:Apache License

@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;// ww  w .jav a2s  . com
    }

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

    client.getLookup().getTopicsUnderNamespace(namespaceName).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 = PatternTopicsConsumerImpl.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(PatternTopicsConsumerImpl.this, Math.min(1, conf.getPatternAutoDiscoveryPeriod()),
            TimeUnit.MINUTES);
}

From source file:org.onosproject.provider.pcep.tunnel.impl.TunnelStatsCollector.java

License:Apache License

@Override
public void run(Timeout timeout) throws Exception {
    if (stopped || timeout.isCancelled()) {
        return;/*from  w w  w .java 2 s  .  c  om*/
    }
    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);
    }

}

From source file:org.traccar.database.ConnectionManager.java

License:Apache License

public void updateDevice(final long deviceId, String status, Date time) {
    Device device = Context.getIdentityManager().getById(deviceId);
    if (device == null) {
        return;//from   w  w w  .  j a  va 2s  .c  o m
    }

    String oldStatus = device.getStatus();
    device.setStatus(status);

    if (enableStatusEvents && !status.equals(oldStatus)) {
        String eventType;
        Map<Event, Position> events = new HashMap<>();
        switch (status) {
        case Device.STATUS_ONLINE:
            eventType = Event.TYPE_DEVICE_ONLINE;
            break;
        case Device.STATUS_UNKNOWN:
            eventType = Event.TYPE_DEVICE_UNKNOWN;
            if (updateDeviceState) {
                events.putAll(updateDeviceState(deviceId));
            }
            break;
        default:
            eventType = Event.TYPE_DEVICE_OFFLINE;
            if (updateDeviceState) {
                events.putAll(updateDeviceState(deviceId));
            }
            break;
        }
        events.put(new Event(eventType, deviceId), null);
        Context.getNotificationManager().updateEvents(events);
    }

    Timeout timeout = timeouts.remove(deviceId);
    if (timeout != null) {
        timeout.cancel();
    }

    if (time != null) {
        device.setLastUpdate(time);
    }

    if (status.equals(Device.STATUS_ONLINE)) {
        timeouts.put(deviceId, GlobalTimer.getTimer().newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) {
                if (!timeout.isCancelled()) {
                    updateDevice(deviceId, Device.STATUS_UNKNOWN, null);
                }
            }
        }, deviceTimeout, TimeUnit.MILLISECONDS));
    }

    try {
        Context.getDeviceManager().updateDeviceStatus(device);
    } catch (SQLException error) {
        LOGGER.warn("Update device status error", error);
    }

    updateDevice(device);

    if (status.equals(Device.STATUS_ONLINE) && !oldStatus.equals(Device.STATUS_ONLINE)) {
        Context.getCommandsManager().sendQueuedCommands(getActiveDevice(deviceId));
    }
}

From source file:qunar.tc.qmq.service.HeartbeatManager.java

License:Apache License

public void refreshHeartbeat(T key, TimerTask task, long timeout, TimeUnit unit) {
    Timeout context = timer.newTimeout(task, timeout, unit);
    final Timeout old = timeouts.put(key, context);
    if (old != null && !old.isCancelled() && !old.isExpired()) {
        old.cancel();//from  ww w.ja v a 2  s  . c  o m
    }
}