Example usage for java.util TimerTask TimerTask

List of usage examples for java.util TimerTask TimerTask

Introduction

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

Prototype

protected TimerTask() 

Source Link

Document

Creates a new timer task.

Usage

From source file:com.irccloud.android.fragment.MessageViewFragment.java

private synchronized void insertEvent(final MessageAdapter adapter, EventsDataSource.Event event,
        boolean backlog, boolean nextIsGrouped) {
    synchronized (adapterLock) {
        try {/*from  w  w  w . ja  va  2s.  c  o  m*/
            boolean colors = false;
            if (!event.self && conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null
                    && conn.getUserInfo().prefs.has("nick-colors")
                    && conn.getUserInfo().prefs.getBoolean("nick-colors"))
                colors = true;

            long start = System.currentTimeMillis();
            if (event.eid <= buffer.min_eid) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        headerView.setVisibility(View.GONE);
                        backlogFailed.setVisibility(View.GONE);
                        loadBacklogButton.setVisibility(View.GONE);
                    }
                });
            }
            if (earliest_eid == 0 || event.eid < earliest_eid)
                earliest_eid = event.eid;

            String type = event.type;
            long eid = event.eid;

            if (type.startsWith("you_"))
                type = type.substring(4);

            if (type.equals("joined_channel") || type.equals("parted_channel") || type.equals("nickchange")
                    || type.equals("quit") || type.equals("user_channel_mode") || type.equals("socket_closed")
                    || type.equals("connecting_cancelled") || type.equals("connecting_failed")) {
                boolean shouldExpand = false;
                collapsedEvents.showChan = !buffer.type.equals("channel");
                if (conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
                    if (hiddenMap == null) {
                        if (buffer.type.equals("channel")) {
                            if (conn.getUserInfo().prefs.has("channel-hideJoinPart"))
                                hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hideJoinPart");
                        } else {
                            if (conn.getUserInfo().prefs.has("buffer-hideJoinPart"))
                                hiddenMap = conn.getUserInfo().prefs.getJSONObject("buffer-hideJoinPart");
                        }
                    }

                    if (hiddenMap != null && hiddenMap.has(String.valueOf(buffer.bid))
                            && hiddenMap.getBoolean(String.valueOf(buffer.bid))) {
                        adapter.removeItem(event.eid);
                        if (!backlog)
                            adapter.notifyDataSetChanged();
                        return;
                    }

                    if (expandMap == null) {
                        if (buffer.type.equals("channel")) {
                            if (conn.getUserInfo().prefs.has("channel-expandJoinPart"))
                                expandMap = conn.getUserInfo().prefs.getJSONObject("channel-expandJoinPart");
                        } else if (buffer.type.equals("console")) {
                            if (conn.getUserInfo().prefs.has("buffer-expandDisco"))
                                expandMap = conn.getUserInfo().prefs.getJSONObject("buffer-expandDisco");
                        } else {
                            if (conn.getUserInfo().prefs.has("buffer-expandJoinPart"))
                                expandMap = conn.getUserInfo().prefs.getJSONObject("buffer-expandJoinPart");
                        }
                    }

                    if (expandMap != null && expandMap.has(String.valueOf(buffer.bid))
                            && expandMap.getBoolean(String.valueOf(buffer.bid))) {
                        shouldExpand = true;
                    }
                }

                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(eid / 1000);

                if (shouldExpand)
                    expandedSectionEids.clear();

                if (event.type.equals("socket_closed") || event.type.equals("connecting_failed")
                        || event.type.equals("connecting_cancelled")) {
                    EventsDataSource.Event last = EventsDataSource.getInstance().getEvent(lastCollapsedEid,
                            buffer.bid);
                    if (last != null && !last.type.equals("socket_closed")
                            && !last.type.equals("connecting_failed")
                            && !last.type.equals("connecting_cancelled"))
                        currentCollapsedEid = -1;
                } else {
                    EventsDataSource.Event last = EventsDataSource.getInstance().getEvent(lastCollapsedEid,
                            buffer.bid);
                    if (last != null
                            && (last.type.equals("socket_closed") || last.type.equals("connecting_failed")
                                    || last.type.equals("connecting_cancelled")))
                        currentCollapsedEid = -1;
                }

                if (currentCollapsedEid == -1 || calendar.get(Calendar.DAY_OF_YEAR) != lastCollapsedDay
                        || shouldExpand) {
                    collapsedEvents.clear();
                    currentCollapsedEid = eid;
                    lastCollapsedDay = calendar.get(Calendar.DAY_OF_YEAR);
                }

                if (!collapsedEvents.showChan)
                    event.chan = buffer.name;

                if (!collapsedEvents.addEvent(event))
                    collapsedEvents.clear();

                if ((currentCollapsedEid == event.eid || shouldExpand) && type.equals("user_channel_mode")) {
                    event.color = R.color.row_message_label;
                    event.bg_color = R.color.status_bg;
                } else {
                    event.color = R.color.timestamp;
                    event.bg_color = R.color.message_bg;
                }

                String msg;
                if (expandedSectionEids.contains(currentCollapsedEid)) {
                    CollapsedEventsList c = new CollapsedEventsList();
                    c.showChan = collapsedEvents.showChan;
                    c.setServer(server);
                    c.addEvent(event);
                    msg = c.getCollapsedMessage();
                    if (!nextIsGrouped) {
                        String group_msg = collapsedEvents.getCollapsedMessage();
                        if (group_msg == null && type.equals("nickchange")) {
                            group_msg = event.old_nick + "  <b>" + event.nick + "</b>";
                        }
                        if (group_msg == null && type.equals("user_channel_mode")) {
                            if (event.from != null && event.from.length() > 0)
                                msg = collapsedEvents.formatNick(event.nick, event.target_mode, false)
                                        + " was set to <b>" + event.diff + "</b> by <b>"
                                        + collapsedEvents.formatNick(event.from, event.from_mode, false)
                                        + "</b>";
                            else
                                msg = collapsedEvents.formatNick(event.nick, event.target_mode, false)
                                        + " was set to <b>" + event.diff + "</b> by the server <b>"
                                        + event.server + "</b>";
                            currentCollapsedEid = eid;
                        }
                        EventsDataSource.Event heading = new EventsDataSource.Event();
                        heading.type = "__expanded_group_heading__";
                        heading.cid = event.cid;
                        heading.bid = event.bid;
                        heading.eid = currentCollapsedEid - 1;
                        heading.group_msg = group_msg;
                        heading.color = R.color.timestamp;
                        heading.bg_color = R.color.message_bg;
                        heading.linkify = false;
                        adapter.addItem(currentCollapsedEid - 1, heading);
                        if (event.type.equals("socket_closed") || event.type.equals("connecting_failed")
                                || event.type.equals("connecting_cancelled")) {
                            EventsDataSource.Event last = EventsDataSource.getInstance()
                                    .getEvent(lastCollapsedEid, buffer.bid);
                            if (last != null)
                                last.row_type = ROW_MESSAGE;
                            event.row_type = ROW_SOCKETCLOSED;
                        }
                    }
                    event.timestamp = null;
                } else {
                    msg = (nextIsGrouped && currentCollapsedEid != event.eid) ? ""
                            : collapsedEvents.getCollapsedMessage();
                }

                if (msg == null && type.equals("nickchange")) {
                    msg = event.old_nick + "  <b>" + event.nick + "</b>";
                }
                if (msg == null && type.equals("user_channel_mode")) {
                    if (event.from != null && event.from.length() > 0)
                        msg = collapsedEvents.formatNick(event.nick, event.target_mode, false)
                                + " was set to <b>" + event.diff + "</b> by <b>"
                                + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b>";
                    else
                        msg = collapsedEvents.formatNick(event.nick, event.target_mode, false)
                                + " was set to <b>" + event.diff + "</b> by the server <b>" + event.server
                                + "</b>";
                    currentCollapsedEid = eid;
                }
                if (!expandedSectionEids.contains(currentCollapsedEid)) {
                    if (eid != currentCollapsedEid) {
                        event.color = R.color.timestamp;
                        event.bg_color = R.color.message_bg;
                    }
                    eid = currentCollapsedEid;
                }
                event.group_msg = msg;
                event.html = null;
                event.formatted = null;
                event.linkify = false;
                lastCollapsedEid = event.eid;
                if (buffer.type.equals("console") && !event.type.equals("socket_closed")
                        && !event.type.equals("connecting_failed")
                        && !event.type.equals("connecting_cancelled")) {
                    currentCollapsedEid = -1;
                    lastCollapsedEid = -1;
                    collapsedEvents.clear();
                }
            } else {
                currentCollapsedEid = -1;
                lastCollapsedEid = -1;
                collapsedEvents.clear();
                if (event.html == null) {
                    if (event.from != null && event.from.length() > 0)
                        event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, colors)
                                + "</b> " + event.msg;
                    else if (event.type.equals("buffer_msg") && event.server != null
                            && event.server.length() > 0)
                        event.html = "<b>" + event.server + "</b> " + event.msg;
                    else
                        event.html = event.msg;
                }
            }

            String from = event.from;
            if (from == null || from.length() == 0)
                from = event.nick;

            if (from != null && event.hostmask != null
                    && (type.equals("buffer_msg") || type.equals("buffer_me_msg") || type.equals("notice")
                            || type.equals("channel_invite") || type.equals("callerid")
                            || type.equals("wallops"))
                    && buffer.type != null && !buffer.type.equals("conversation")) {
                String usermask = from + "!" + event.hostmask;
                if (ignore.match(usermask)) {
                    if (unreadTopView != null && unreadTopView.getVisibility() == View.GONE
                            && unreadBottomView != null && unreadBottomView.getVisibility() == View.GONE) {
                        if (heartbeatTask != null)
                            heartbeatTask.cancel(true);
                        heartbeatTask = new HeartbeatTask();
                        heartbeatTask.execute((Void) null);
                    }
                    return;
                }
            }

            switch (type) {
            case "channel_mode":
                if (event.nick != null && event.nick.length() > 0)
                    event.html = event.msg + " by <b>"
                            + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b>";
                else if (event.server != null && event.server.length() > 0)
                    event.html = event.msg + " by the server <b>" + event.server + "</b>";
                break;
            case "buffer_me_msg":
                event.html = " <i><b>" + collapsedEvents.formatNick(event.nick, event.from_mode, colors)
                        + "</b> " + event.msg + "</i>";
                break;
            case "notice":
                if (event.from != null && event.from.length() > 0)
                    event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, false)
                            + "</b> ";
                else
                    event.html = "";
                if (buffer.type.equals("console") && event.to_chan && event.chan != null
                        && event.chan.length() > 0) {
                    event.html += event.chan + "&#xfe55; " + event.msg;
                } else {
                    event.html += event.msg;
                }
                break;
            case "kicked_channel":
                event.html = "? ";
                if (event.type.startsWith("you_"))
                    event.html += "You";
                else
                    event.html += "<b>" + collapsedEvents.formatNick(event.old_nick, null, false) + "</b>";
                if (event.type.startsWith("you_"))
                    event.html += " were";
                else
                    event.html += " was";
                if (event.hostmask != null && event.hostmask.length() > 0)
                    event.html += " kicked by <b>"
                            + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b> ("
                            + event.hostmask + ")";
                else
                    event.html += " kicked by the server <b>" + event.nick + "</b>";
                if (event.msg != null && event.msg.length() > 0)
                    event.html += ": " + event.msg;
                break;
            case "callerid":
                event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b> ("
                        + event.hostmask + ") " + event.msg + " Tap to accept.";
                break;
            case "channel_mode_list_change":
                if (event.from.length() == 0) {
                    if (event.nick != null && event.nick.length() > 0)
                        event.html = "<b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false)
                                + "</b> " + event.msg;
                    else if (event.server != null && event.server.length() > 0)
                        event.html = "The server <b>" + event.server + "</b> " + event.msg;
                }
                break;
            }

            adapter.addItem(eid, event);
            if (!backlog)
                adapter.notifyDataSetChanged();

            long time = (System.currentTimeMillis() - start);
            if (avgInsertTime == 0)
                avgInsertTime = time;
            avgInsertTime += time;
            avgInsertTime /= 2.0;
            //Log.i("IRCCloud", "Average insert time: " + avgInsertTime);
            if (!backlog && buffer.scrolledUp && !event.self && event.isImportant(type)) {
                if (newMsgTime == 0)
                    newMsgTime = System.currentTimeMillis();
                newMsgs++;
                if (event.highlight)
                    newHighlights++;
                update_unread();
                adapter.insertLastSeenEIDMarker();
                adapter.notifyDataSetChanged();
            }
            if (!backlog && !buffer.scrolledUp) {
                getListView().setSelection(adapter.getCount() - 1);
                if (tapTimer != null) {
                    tapTimer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        getListView().setSelection(adapter.getCount() - 1);
                                    } catch (Exception e) {
                                        //List view isn't ready yet
                                    }
                                }
                            });
                        }
                    }, 200);
                }
            }

            if (!backlog && event.highlight
                    && !getActivity().getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) {
                Toast.makeText(getActivity(), "Double-tap a message to quickly reply to the sender",
                        Toast.LENGTH_LONG).show();
                SharedPreferences.Editor editor = getActivity().getSharedPreferences("prefs", 0).edit();
                editor.putBoolean("mentionTip", true);
                editor.commit();
            }
            if (!backlog) {
                int markerPos = adapter.getLastSeenEIDPosition();
                if (markerPos > 0 && getListView().getFirstVisiblePosition() > markerPos) {
                    unreadTopLabel.setText(
                            (getListView().getFirstVisiblePosition() - markerPos) + " unread messages");
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:de.bwravencl.controllerbuddy.gui.Main.java

private void startOverlayTimerTask() {
    stopOverlayTimerTask();//w w w.j av a2  s . c  om

    overlayTimerTask = new TimerTask() {

        @Override
        public void run() {
            SwingUtilities.invokeLater(() -> {
                if (!isModalDialogShowing()) {
                    if (overlayFrame != null) {
                        overlayFrame.setAlwaysOnTop(false);
                        overlayFrame.setAlwaysOnTop(true);
                    }

                    if (onScreenKeyboard.isVisible()) {
                        onScreenKeyboard.setAlwaysOnTop(false);
                        onScreenKeyboard.setAlwaysOnTop(true);
                    }
                }

                final var maxWindowBounds = GraphicsEnvironment.getLocalGraphicsEnvironment()
                        .getMaximumWindowBounds();
                if (!maxWindowBounds.equals(prevMaxWindowBounds)) {
                    prevMaxWindowBounds = maxWindowBounds;

                    updateOverlayLocation(maxWindowBounds);
                    onScreenKeyboard.updateLocation();
                }

                repaintOverlay();
            });
        }
    };

    timer.schedule(overlayTimerTask, OVERLAY_POSITION_UPDATE_INTERVAL, OVERLAY_POSITION_UPDATE_INTERVAL);
}

From source file:com.lfv.lanzius.server.LanziusServer.java

private void menuChoiceNetworkMonitor() {
    if (networkStatusTimer != null) {
        networkStatusTimer.cancel();//  w w  w.j  a  v a2  s .c om
        networkStatusTimer = null;
        log.debug("Stopped network connection monitoring");
    } else {
        networkStatusTimer = new Timer();
        networkStatusTimer.schedule(new TimerTask() {
            public void run() {
                if (serverStartedDate != null) {
                    log.debug("Check network connection status");
                }
                if (serverStartedDate != null && networkManager.connectionProblem()) {
                    log.error("Possible network connection problem detected, restart server!");
                    try {
                        serverRestart();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }, 30000, 5000);
        log.debug("Started network connection monitoring");
    }
    itemServerMonitor.setSelected(networkStatusTimer != null);
}

From source file:com.couchbase.lite.router.Router.java

private void startHeartbeat(long interval) {
    if (interval <= 0)
        return;/*from   w w  w  . j  a v  a 2 s. c o  m*/

    stopHeartbeat();
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            synchronized (databaseChangesLongpollLock) {
                OutputStream os = connection.getResponseOutputStream();
                if (os != null) {
                    try {
                        Log.v(TAG, "[%s] Sent heart beat!", this);
                        os.write("\r\n".getBytes());
                        os.flush();
                    } catch (IOException e) {
                        Log.w(TAG, "IOException writing to internal streams: " + e.getMessage());
                    } finally {
                        // no close outputstream, OutputStream might be re-used
                    }
                }
            }
        }
    }, interval, interval);
}

From source file:com.silentcircle.silenttext.application.SilentTextApplication.java

private void rescheduleAutoDisconnect() {

    cancelAutoDisconnect();//from  w  ww. j av a  2 s.c  o m

    if (ServiceConfiguration.getInstance().xmpp.background || !GCMService.isAvailable(this)) {
        return;
    }

    autoDisconnect = new TimerTask() {

        @Override
        public void run() {
            logout();
        }

    };

    timer.schedule(autoDisconnect, 5 * 1000L);

}

From source file:com.lfv.lanzius.application.Controller.java

public synchronized void serverConnected(boolean accepted) {
    if (accepted) {
        log.info("Connected to server " + serverSocketAddr);
        state = CLIENT_STATE_CONNECTED;//w  w  w .ja va2  s  .c om
        dbgListThreads();
        // Wait for control start to create visuals
        log.debug("Waiting for start session packet from server");
    } else {
        if (reconnectPrintCount > 0) {
            log.info("Unable to connect to server");
        }
        if (reconnectPrintCount >= 0) {
            reconnectPrintCount--;
        }
        if (timer != null) {
            if (reconnectPrintCount > 0)
                log.info("Reconnecting in " + (DELAY_RECONNECT / 1000) + " seconds...");
            timer.schedule(new TimerTask() {
                public void run() {
                    if (networkManager != null) {
                        if (reconnectPrintCount > 0)
                            log.info("Connecting to server...");
                        networkManager.serverConnect();
                    }
                }
            }, DELAY_RECONNECT);
            if (reconnectPrintCount == 0) {
                log.info("Entering silent mode, still trying to connect to server...");
                reconnectPrintCount = -1;
            }
        } else {
            log.error("Unexpected shutdown, timer is null!");
            shutdown(true);
        }
    }
}

From source file:com.silentcircle.silenttext.application.SilentTextApplication.java

private void rescheduleAutoLock() {

    cancelAutoLock();//from   www . j  a  v  a2s.c o m

    int timeout = OptionsDrawer.getInactivityTimeout(this);

    if (timeout > 10) {

        autoLock = new TimerTask() {

            @Override
            public void run() {
                lock();
            }

        };

        timer.schedule(autoLock, timeout * 1000L);

    }

}

From source file:com.silentcircle.silenttext.application.SilentTextApplication.java

private TimerTask respondToNetworkStateChange() {

    if (respondToNetworkStateChange != null) {
        respondToNetworkStateChange.cancel();
        respondToNetworkStateChange = null;
    }//from  w  w  w  .  j av  a 2  s.c o  m

    final boolean wasConnected = connected;
    respondToNetworkStateChange = new TimerTask() {

        @Override
        public void run() {
            if (autoDisconnect != null) {
                return;
            }
            if (wasConnected != connected) {
                return;
            }
            if (connected) {
                if (isUnlocked() && isUserKeyUnlocked()) {
                    XMPPTransport client = getXMPPTransport();
                    if (client == null) {
                        Server server = getServer("xmpp");
                        createXMPPTransportAsync(server != null ? server.getCredential() : null);
                    }
                } else {
                    sendBroadcast(Action.CONNECT.intent(), Manifest.permission.READ);
                }
            }
        }
    };

    return respondToNetworkStateChange;

}

From source file:com.lfv.lanzius.application.Controller.java

public synchronized void sessionStart() {
    if (state != CLIENT_STATE_STARTED && timer != null) {
        log.debug("Start session packet received");
        timer.schedule(new TimerTask() {
            public void run() {
                start();/*from  w  w  w .  j  av a  2 s  . c  o  m*/
            }
        }, DELAY_START + (int) (2 * Math.random() * DELAY_START_VARIANCE) - DELAY_START_VARIANCE);
    }
}