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.rzo.netty.ahessian.heartbeat.HeartbeatHandlerInbound.java

License:Apache License

public HeartbeatHandlerInbound(final String name, final Timer timer, final long timeout) {
    _name = name;/* w  ww .j  av  a  2s . c o  m*/
    final TimerTask task = new TimerTask() {
        public void run(Timeout nTimeout) throws Exception {
            if (((getLastCalled() + timeout) <= System.currentTimeMillis()) && isConnected())
                try {
                    _action.timedOut(_ctx);
                } catch (Exception e) {
                    Constants.ahessianLogger.warn("", e);
                }
        }

    };
    _intervalTimer = new IntervalTimer(timer, task, timeout);
}

From source file:org.rzo.netty.ahessian.heartbeat.IntervalTimer.java

License:Apache License

public IntervalTimer(final Timer timer, final TimerTask task, final long interval) {
    _timer = timer;//from   w  w w .j  av a2  s. c om
    _task = new TimerTask() {

        public void run(Timeout timeout) throws Exception {
            _lock.lock();
            try {
                if (!timeout.equals(getTimeout())) {
                    // System.out.println("other timeout -> ignore");
                    return;
                }
                // System.out.println(new Date()+" timer called " +
                // _name+"/"+_interval);
                try {
                    task.run(timeout);
                } catch (Throwable ex) {
                    ex.printStackTrace();
                }
                if (getTimeout() != null)
                    setTimeout(_timer.newTimeout(this, interval, TimeUnit.MILLISECONDS));
            } finally {
                _lock.unlock();
            }

        }

    };
    _interval = interval;
}

From source file:org.rzo.netty.ahessian.rpc.callback.ServerCallbackProxy.java

License:Apache License

private Object waitForCallbackResult(final Long id, final HessianProxyFuture future) {
    long timeout = 10000;
    if (timeout > 0) {
        TimerTask task = new TimerTask() {

            public void run(Timeout arg0) throws Exception {
                _openCallbackCalls.remove(id);
                future.timedOut();/*  w  w w .ja v  a2s .c  om*/
            }

        };
        future.setTimeout(_timer.newTimeout(task, timeout, TimeUnit.MILLISECONDS));
    }

    try {
        return future.getCallbackResult();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.rzo.netty.ahessian.rpc.client.HessianProxyFactory.java

License:Apache License

/**
 * Send request./*from   w  ww .j  a v a  2 s.  c om*/
 * 
 * @param methodName
 *            the method name
 * @param args
 *            the args
 * @param options
 *            the options
 * 
 * @return the future< object>
 * 
 * @throws InterruptedException
 *             the interrupted exception
 */
synchronized Future<Object> sendRequest(String methodName, Object[] args, Map options)
        throws InterruptedException {
    long t = System.currentTimeMillis();
    if (_blocked)
        throw new RuntimeException("send blocked");
    if (_stop)
        return null;
    Map<Object, Object> headers = options;
    final Long id = new Long(_id);
    _id++;
    headers.put(CALL_ID_HEADER_KEY, id);
    final HessianProxyFuture future = new HessianProxyFuture();
    future.handleCallbacks(args);
    final HessianRPCCallMessage message = new HessianRPCCallMessage(methodName, args, headers, null);
    int i = 0;
    while (_openCalls.size() > MAX_OPEN_CALLS && getChannel() != null) {
        // System.out.println("too many open calls -> wait "+i++);
        Thread.sleep(10);
    }
    _openCalls.put(id, future);
    Integer g = (Integer) options.get("group");
    final Integer group = g == null ? 0 : g;
    long timeout = _pendingCalls.getTimeout(group);
    if (timeout > 0) {
        TimerTask task = new TimerTask() {

            public void run(Timeout arg0) throws Exception {
                _openCalls.remove(id);
                future.timedOut();
            }

        };
        future.setTimeout(_timer.newTimeout(task, timeout, TimeUnit.MILLISECONDS));
    }
    Channel channel = null;
    /*
     * while ((channel = getChannel()) == null) { _lock.lock(); try {
     * _connected.await(100, TimeUnit.MILLISECONDS); } finally {
     * _lock.unlock(); } }
     */
    channel = getChannel();
    if (channel == null)
        throw new RuntimeException("channel closed");
    while (!channel.isWritable() && channel.isActive()) {
        // System.out.println("channel wait call "+Thread.currentThread().getName());
        Thread.sleep(100);
    }
    channel.write(message);
    // System.out.println("sendRequest "+(System.currentTimeMillis()-t));

    return future;
}

From source file:org.rzo.netty.ahessian.rpc.client.ReconnectHandler.java

License:Apache License

private synchronized void scheduleReconnect() {
    if (_stop)/*w  w w  .  j a  v  a2s . c o  m*/
        return;
    if (_timeout != null)
        return;
    Constants.ahessianLogger.warn("channel closed wait to reconnect ...");
    _retryCounter++;
    long retryIntervall = Math.min(RECONNECT_DELAY * _retryCounter, MAX_RECONNECT_DELAY);
    _timeout = _timer.newTimeout(new TimerTask() {
        public void run(Timeout timeout) throws Exception {
            _timeout = null;
            connect(_bootstrap.getBootstrap());

        }
    }, retryIntervall, TimeUnit.MILLISECONDS);
}

From source file:org.rzo.netty.ahessian.session.ServerSessionFilter.java

License:Apache License

@Override
public void channelInactive(final ChannelHandlerContext ctx) throws Exception {

    _hasSession = false;//from   w ww  .  j  a  va  2  s. co  m
    ctx.channel().attr(SESSION).get().close();
    final String sessionId = ctx.channel().attr(SESSION).get().getId();
    Constants.ahessianLogger.info("Session disconnected: " + sessionId);
    _sessionId = "";
    _channel = null;
    // remove the session if the client does not reconnect within timeout
    if (_sessionTimeout > 0) {
        Timeout timeOut = _timer.newTimeout(new TimerTask() {

            public void run(Timeout arg0) throws Exception {
                ctx.channel().attr(SESSION).get().invalidate();
                _factory.removeSession(sessionId);
                _sessionPipelines.remove(sessionId);
                _valid = false;
                Constants.ahessianLogger.warn(ctx.channel() + " session timed out: " + sessionId);
            }

        }, _sessionTimeout, TimeUnit.MILLISECONDS);
        ctx.channel().attr(SESSION).get().setTimeOut(timeOut);
    }
    ctx.fireChannelInactive();
}

From source file:org.rzo.netty.ahessian.utils.TimedBlockingPriorityQueue.java

License:Apache License

public boolean offer(final T e, int group) {
    boolean result = false;
    _lock.lock();//from  w  w  w  .ja v a 2 s  .  c o  m
    try {
        // if (_size == 0)
        // System.out.println("LRUQueue not empty: "+ _name);
        _size++;
        if (group >= _queues.length) {
            Constants.ahessianLogger.warn("group " + group + " not defined -> using group 0");
            group = 0;
        }
        final LinkedList<T> q = _queues[group];
        result = q.offer((T) e);
        if (q.size() >= _sizes[group]) {
            // if queue is full remove an element and undo its timer
            T o = q.remove();
            Timeout timer = _timers.remove(o);
            if (timer != null)
                timer.cancel();
            Constants.ahessianLogger.warn("queue overflow -> removed " + e);
        }
        if (result)
            _last = e;

        if (_timer != null && result && _timeouts[group] > 0) {
            Timeout timer = _timer.newTimeout(new TimerTask() {

                public void run(Timeout arg0) throws Exception {
                    _lock.lock();
                    try {
                        q.remove(e);
                        Constants.ahessianLogger.warn("message timed out -> removed from queue " + e);
                    } finally {
                        _lock.unlock();
                    }
                }

            }, _timeouts[group], TimeUnit.MILLISECONDS);
        }

        if (result && waiting)
            try {
                _hasData.signal();
            } catch (Exception ex) {
                Constants.ahessianLogger.warn("", ex);
            }

    } finally {
        _lock.unlock();
    }
    return result;
}

From source file:org.rzo.yajsw.script.AbstractScript.java

License:Apache License

synchronized public void executeWithTimeout(final String line) {
    if (!checkRemainConc()) {
        log("script: " + _name + " : too many concurrent invocations -> abort execution");
        return;/*from  ww  w.j a v  a 2  s . c o m*/
    }
    Object result = null;
    _timerTimeout = TIMER.newTimeout(new TimerTask() {

        public void run(Timeout arg0) throws Exception {
            log("script takes too long -> interrupt");
            try {
                interrupt();
            } catch (Throwable e) {

            }
        }

    }, _timeout, TimeUnit.MILLISECONDS);
    _future = EXECUTOR.submit(new Callable<Object>() {
        public Object call() {
            Object result = execute(line);
            if (_timerTimeout != null)
                _timerTimeout.cancel();
            _timerTimeout = null;
            _remainingConcInvocations.incrementAndGet();
            log("executed script: " + _name + " " + _remainingConcInvocations);
            return result;
        }
    });
    Thread.yield();
}

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;// ww w.  ja  v  a2 s  . 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.consumer.pull.SendMessageBackImpl.java

License:Apache License

public void sendBackAndCompleteNack(final int nextRetryCount, final BaseMessage message,
        final AckEntry ackEntry) {
    final BrokerClusterInfo brokerCluster = brokerService.getClusterBySubject(ClientType.PRODUCER,
            message.getSubject());/* w w w .j  a  v  a  2s .c om*/
    final SendMessageBack.Callback callback = new SendMessageBack.Callback() {
        private final int retryTooMuch = brokerCluster.getGroups().size() * 2;
        private final AtomicInteger retryNumOnFail = new AtomicInteger(0);

        @Override
        public void success() {
            ackEntry.completed();
        }

        @Override
        public void fail(Throwable e) {
            if (retryNumOnFail.incrementAndGet() > retryTooMuch) {
                if (e instanceof SendMessageBackException) {
                    LOGGER.error("send message back fail, and retry {} times after {} seconds. exception: {}",
                            retryNumOnFail.get(), SEND_BACK_DELAY_SECONDS, e.getMessage());
                } else {
                    LOGGER.error("send message back fail, and retry {} times after {} seconds",
                            retryNumOnFail.get(), SEND_BACK_DELAY_SECONDS, e);
                }
                final SendMessageBack.Callback callback1 = this;
                TimerUtil.newTimeout(new TimerTask() {
                    @Override
                    public void run(Timeout timeout) {
                        SendMessageBackImpl.this.sendBackAndCompleteNack(message, callback1);
                    }
                }, SEND_BACK_DELAY_SECONDS, TimeUnit.SECONDS);
            } else {
                if (e instanceof SendMessageBackException) {
                    LOGGER.error("send message back fail, and retry {} times. exception: {}",
                            retryNumOnFail.get(), SEND_BACK_DELAY_SECONDS, e.getMessage());
                } else {
                    LOGGER.error("send message back fail, and retry {} times", retryNumOnFail.get(),
                            SEND_BACK_DELAY_SECONDS, e);
                }
                SendMessageBackImpl.this.sendBackAndCompleteNack(message, this);
            }
        }
    };
    final BrokerGroupInfo brokerGroup = brokerLoadBalance.loadBalance(brokerCluster, null);
    sendBack(brokerGroup, message, callback, ClientType.PRODUCER);
}