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.moilioncircle.redis.replicator.RedisSocketReplicator.java

/**
 * PSYNC//from   ww w. j  av a  2s  . c om
 *
 * @throws IOException when read timeout or connect timeout
 */
@Override
public void open() throws IOException {
    worker.start();
    for (int i = 0; i < configuration.getRetries() || configuration.getRetries() <= 0; i++) {
        try {
            connect();

            if (configuration.getAuthPassword() != null)
                auth(configuration.getAuthPassword());

            sendSlavePort();

            sendSlaveIp();

            sendSlaveCapa();

            //reset retries
            i = 0;

            logger.info("PSYNC " + configuration.getMasterRunId() + " "
                    + String.valueOf(configuration.getOffset()));
            send("PSYNC".getBytes(), configuration.getMasterRunId().getBytes(),
                    String.valueOf(configuration.getOffset()).getBytes());
            final String reply = (String) reply();

            SyncMode syncMode = trySync(reply);
            //bug fix.
            if (syncMode == SyncMode.PSYNC && connected.get()) {
                //heart beat send REPLCONF ACK ${slave offset}
                synchronized (this) {
                    heartBeat = new Timer("heart beat");
                    //bug fix. in this point closed by other thread. multi-thread issue
                    heartBeat.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            try {
                                send("REPLCONF".getBytes(), "ACK".getBytes(),
                                        String.valueOf(configuration.getOffset()).getBytes());
                            } catch (IOException e) {
                                //NOP
                            }
                        }
                    }, configuration.getHeartBeatPeriod(), configuration.getHeartBeatPeriod());
                    logger.info("heart beat started.");
                }
            }
            //sync command
            while (connected.get()) {
                Object obj = replyParser.parse(new OffsetHandler() {
                    @Override
                    public void handle(long len) {
                        configuration.addOffset(len);
                    }
                });
                //command
                if (obj instanceof Object[]) {
                    if (configuration.isVerbose() && logger.isDebugEnabled())
                        logger.debug(Arrays.deepToString((Object[]) obj));

                    Object[] command = (Object[]) obj;
                    CommandName cmdName = CommandName.name((String) command[0]);
                    Object[] params = new Object[command.length - 1];
                    System.arraycopy(command, 1, params, 0, params.length);

                    final CommandParser<? extends Command> operations;
                    //if command do not register. ignore
                    if ((operations = commands.get(cmdName)) == null)
                        continue;

                    //do command replyParser
                    Command parsedCommand = operations.parse(cmdName, params);

                    //submit event
                    this.submitEvent(parsedCommand);
                } else {
                    if (logger.isInfoEnabled())
                        logger.info("Redis reply:" + obj);
                }
            }
            //connected = false
            break;
        } catch (/*bug fix*/IOException | InterruptedException e) {
            //close socket manual
            if (!connected.get()) {
                break;
            }
            logger.error("socket error", e);
            //connect refused
            //connect timeout
            //read timeout
            //connect abort
            //server disconnect connection EOFException
            close();
            //retry psync in next loop.
            logger.info("reconnect to redis-server. retry times:" + (i + 1));
            try {
                Thread.sleep(configuration.getRetryTimeInterval());
            } catch (InterruptedException e1) {
                //non interrupted
                logger.error("error", e1);
            }
        }
    }
    //
    if (worker != null && !worker.isClosed())
        worker.close();
}

From source file:DynamiskDemo2.java

/**
 * Constructs a new demonstration application.
 *
 * @param title  the frame title.//w ww .j  a v  a 2  s  .co  m
 */
public DynamiskDemo2(final String title) {

    super(title);
    this.series = new XYSeries(title, false, false);
    final XYSeriesCollection dataset = new XYSeriesCollection(this.series);
    final JFreeChart chart = createChart(dataset);

    final ChartPanel chartPanel = new ChartPanel(chart);
    final JButton button = new JButton("Add New Data Item");
    button.setActionCommand("ADD_DATA");
    button.addActionListener(this);

    final JPanel content = new JPanel(new BorderLayout());
    content.add(chartPanel);
    content.add(button, BorderLayout.SOUTH);
    chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
    setContentPane(content);
    String fil = "C:" + File.separator + "Users" + File.separator + "madso" + File.separator + "Documents"
            + File.separator + "!Privat" + File.separator + "DTU 2016-2020" + File.separator + "MATLAB";
    String filnavn = "EKGdata";
    try {
        Scanner sc = new Scanner(new FileReader(fil + File.separator + filnavn));

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                if (sc.hasNext()) {
                    final double newItem = Double.parseDouble(sc.next());
                    series.add(x, newItem);
                    x += 10;
                }
            }

        }, 100, 2);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.arrow.acs.client.api.ConnectionManager.java

private void restartExpiredTimer() {
    String method = "restartExpiredTimer";

    if (checkExpiredTimer != null) {
        logInfo(method, "cancelling current timer ...");
        checkExpiredTimer.cancel();/*  www. jav a  2s  .  c o  m*/
        checkExpiredTimer = null;
    }

    logDebug(method, "checkExpiredConnectionIntervalMs: %d", checkExpiredConnectionIntervalMs);
    if (checkExpiredConnectionIntervalMs > 0) {
        checkExpiredTimer = new Timer(true);
        checkExpiredTimer.scheduleAtFixedRate(new TimerTask() {
            AtomicBoolean running = new AtomicBoolean(false);

            @Override
            public void run() {
                if (connectionManager != null) {
                    if (running.compareAndSet(false, true)) {
                        try {
                            logDebug(method, "connectionManager.closeExpiredConnections() ...");
                            connectionManager.closeExpiredConnections();
                        } catch (Throwable t) {
                        }
                    }
                } else {
                    logWarn(method, "connectionManager is not available!");
                }
            }
        }, 0, checkExpiredConnectionIntervalMs);
    } else {
        logWarn(method, "timer is NOT scheduled, checkExpiredConnectionIntervalMs: %d",
                checkExpiredConnectionIntervalMs);
    }
}

From source file:com.predic8.membrane.core.transport.http.ConnectionManager.java

public ConnectionManager(long keepAliveTimeout) {
    this.keepAliveTimeout = keepAliveTimeout;
    this.autoCloseInterval = keepAliveTimeout * 2;
    timer = new Timer("Connection Closer", true);
    timer.schedule(new TimerTask() {
        @Override//from w w  w.  j  av  a2  s .c o m
        public void run() {
            if (closeOldConnections() == 0 && shutdownWhenDone)
                timer.cancel();
        }
    }, autoCloseInterval, autoCloseInterval);
}

From source file:com.microsoft.tfs.core.util.notifications.MessageWindowNotificationManager.java

/**
 * Creates a {@link MessageWindowNotificationManager}. On Windows this
 * constructor creates a hidden message-only window ({@link MessageWindow})
 * to do IPC. On non-Windows platforms, the class sends or receives no
 * messages./*from   w  ww  .  jav  a 2 s.  c  o m*/
 * <p>
 * The application must be in a state where window creation will succeed
 * when this constructor is used.
 */
public MessageWindowNotificationManager() {
    super();

    if (Platform.isCurrentPlatform(Platform.WINDOWS)) {
        this.messageWindow = new MessageWindow(0, MESSAGE_WINDOW_CLASS_NAME, MESSAGE_WINDOW_TITLE,
                NotificationWindowVersion.LATEST, new MessageListener() {
                    @Override
                    public void messageReceived(final int msg, final long wParam, final long lParam) {
                        final Notification n = Notification.fromValue(msg);
                        if (n == null) {
                            log.info(MessageFormat.format(
                                    "Ignoring unknown notification msg={0}, wParam={1}, lParam={2}", //$NON-NLS-1$
                                    Integer.toString(msg), Long.toHexString(wParam), Long.toHexString(lParam)));
                        } else {
                            fireNotificationReceived(n, wParam, lParam);
                        }
                    }
                });

        // Schedule a recurring sender task
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                sendQueuedNotifications();
            }
        }, SEND_DELAY_MS, SEND_PERIOD_MS);
    } else {
        this.messageWindow = null;
    }
}

From source file:burstcoin.observer.service.NodeService.java

public void startCheckNodesTask() {
    timer.schedule(new TimerTask() {
        @Override/*ww  w .  j  av  a2s.c om*/
        public void run() {
            try {
                while (networkBeans == null || networkBeans.isEmpty()) {
                    Thread.sleep(1000 * 60); // wait another minute
                }

                Map<String, Peer> peerLookup = new HashMap<>();
                for (NetworkBean networkBean : networkBeans) {
                    if ("Wallet".equals(networkBean.getType())) {
                        addMissingPeers(networkBean.getUrl(), peerLookup);
                    }
                }

                for (String ip : peerLookup.keySet()) {
                    if (!peerInfoLookup.containsKey(ip)) {
                        PeerInfo peerInfo = getPeerInfo(ip);
                        if (peerInfo != null) {
                            peerInfoLookup.put(ip, peerInfo);
                        }

                        // max 150 requests per minute
                        Thread.sleep(1000 * 60 / 155);
                    }
                }

                BlockchainStatus blockchainStatus = getBlockchainStatus();
                long blockChainTimeInMs = blockchainStatus.getTime() * 1000;
                long blockZeroTime = new Date().getTime() - blockChainTimeInMs;

                Map<String, Integer> nodesByCountry = new HashMap<>();
                List<NodeListBean> nodeBeans = new ArrayList<>();

                List<List> mapData = new ArrayList<>();
                mapData.add(Arrays.asList("Lat", "Long", "Name"));

                for (Map.Entry<String, PeerInfo> entry : peerInfoLookup.entrySet()) {
                    String ip = entry.getKey();
                    PeerInfo peerInfo = entry.getValue();

                    Peer peer = peerLookup.get(ip);
                    if (peer != null) {
                        // todo lastUpdate is not accurate, as it reflects the lastUpdate form first found wallet
                        Date lastUpdate = new Date(blockZeroTime + peer.getLastUpdated() * 1000);
                        long minLastActivity = new Date().getTime() - (1000 * 60 * 60); // min last updated 1h ago

                        // only add peers that were updated in last 12h
                        if (minLastActivity <= lastUpdate.getTime()) {
                            if (!nodesByCountry.containsKey(peerInfo.getCountry())) {
                                nodesByCountry.put(peerInfo.getCountry(), 0);
                            }
                            nodesByCountry.put(peerInfo.getCountry(),
                                    nodesByCountry.get(peerInfo.getCountry()) + 1);

                            nodeBeans.add(new NodeListBean(lastUpdate, peer.getAnnouncedAddress(), ip,
                                    peer.getVersion() != null ? peer.getVersion() : "N/A", peer.getPlatform(),
                                    peerInfo.getCountry() != null ? peerInfo.getCountry() : "N/A",
                                    peerInfo.getRegionName(), peerInfo.getCity(),
                                    peerInfo.getIsp() != null ? peerInfo.getIsp() : "N/A"));

                            mapData.add(Arrays.asList(Float.valueOf(peerInfo.getLat()),
                                    Float.valueOf(peerInfo.getLon()), peer.getAnnouncedAddress()));
                        }
                    }
                }

                Collections.sort(nodeBeans, new Comparator<NodeListBean>() {
                    @Override
                    public int compare(NodeListBean o1, NodeListBean o2) {
                        return o2.getIsp().compareTo(o1.getIsp());
                    }
                });

                Collections.sort(nodeBeans, new Comparator<NodeListBean>() {
                    @Override
                    public int compare(NodeListBean o1, NodeListBean o2) {
                        return o1.getCountry().compareTo(o2.getCountry());
                    }
                });

                Collections.sort(nodeBeans, new Comparator<NodeListBean>() {
                    @Override
                    public int compare(NodeListBean o1, NodeListBean o2) {
                        return o2.getVersion().compareTo(o1.getVersion());
                    }
                });

                // quickfix to put N/A at the end
                List<NodeListBean> atTheEnd = new ArrayList<>();
                for (NodeListBean nodeBean : nodeBeans) {
                    if (nodeBean.getVersion().equals("N/A")) {
                        atTheEnd.add(nodeBean);
                    }
                }
                nodeBeans.removeAll(atTheEnd);
                nodeBeans.addAll(atTheEnd);

                // google geo chart data
                List<List> geoData = new ArrayList<>();
                geoData.add(Arrays.asList("Country", "Nodes"));
                for (Map.Entry<String, Integer> entry : nodesByCountry.entrySet()) {
                    geoData.add(Arrays.asList(entry.getKey(), entry.getValue()));
                }

                // create wellKnownsPeers string
                String wellKnownPeers = "nxt.wellKnownPeers=";
                Set<String> nodeNames = new HashSet<>();
                for (NodeListBean nodeBean : nodeBeans) {
                    nodeNames.add(nodeBean.getIp());
                }
                for (String name : nodeNames) {
                    wellKnownPeers += name + "; ";
                }
                NodeStats nodeStats = new NodeStats(peerInfoLookup.size(), nodeBeans.size(), wellKnownPeers);

                Date now = new Date();
                DecimalFormat f = new DecimalFormat("00");
                for (NodeListBean nodeBean : nodeBeans) {
                    long diff = now.getTime() - nodeBean.getLastUpdate().getTime();
                    long diffSeconds = diff / 1000 % 60;
                    long diffMinutes = diff / (1000 * 60) % 60;
                    long diffHours = diff / (1000 * 60 * 60) % 60;
                    // not 100% accurate
                    nodeBean.setUpdated(f.format(diffHours < 0 ? diffHours * -1 : diffHours) + ":"
                            + f.format(diffMinutes < 0 ? diffMinutes * -1 : diffMinutes) + ":"
                            + f.format(diffSeconds < 0 ? diffSeconds * -1 : diffSeconds));
                }

                publisher.publishEvent(new NodeUpdateEvent(nodeBeans, nodeStats, geoData, mapData));
            } catch (Exception e) {
                LOG.error("Failed update nodes!", e);
            }
        }
    }, ObserverProperties.getNetworkRefreshInterval(), ObserverProperties.getNodeRefreshInterval());
}

From source file:com.mydlp.ui.service.LicenseServiceImpl.java

protected void scheduleLicenseCheck(final int delay) {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {
            scheduleLicenseCheckFun();/*from  w w w .j ava  2s.  c  om*/
            if (!licenseAcquired && retryCounter > 0) {
                retryCounter--;
                scheduleLicenseCheck(delay);
            }
        }
    }, delay);
}

From source file:com.github.woonsan.commons.scxml.examples.stopwatch.StopWatchFrame.java

private void initUI() {
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    setContentPane(mainPanel);//w  w w .j  a  va 2 s.c  o m

    JPanel contentPanel = new JPanel();
    contentPanel.setLayout(new FlowLayout());
    displayLabel = new JLabel("0:00:00,000");
    contentPanel.add(displayLabel, BorderLayout.CENTER);

    mainPanel.add(contentPanel, BorderLayout.CENTER);

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout());

    startButton = createButton("START", "Start");
    buttonPanel.add(startButton);

    stopButton = createButton("STOP", "Stop");
    stopButton.setEnabled(false);
    buttonPanel.add(stopButton);

    resetButton = createButton("RESET", "Reset");
    resetButton.setEnabled(false);
    buttonPanel.add(resetButton);

    mainPanel.add(buttonPanel, BorderLayout.SOUTH);

    pack();

    setLocation(200, 200);
    setSize(260, 80);

    setResizable(true);
    setVisible(true);

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    Timer displayTimer = new Timer();
    displayTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            displayLabel.setText(stopWatch.getDisplay());
        }
    }, 100, 100);
}

From source file:dk.netarkivet.monitor.distribute.JMSMonitorRegistryClient.java

/** Register this host for monitoring.
 * Once this method is called it will reregister for monitoring every
 * minute, to ensure the scheduling is done.
 * If called again, it will restart the timer that registers the host.
 * @param localHostName The name of the host.
 * @param jmxPort The port for JMX connections to the host.
 * @param rmiPort The port for RMI connections for JMX communication.
 * @throws ArgumentNotValid on null or empty hostname, or negative port
 * numbers./* w w w. j a  v a  2 s.  c  o  m*/
 */
public synchronized void register(final String localHostName, final int jmxPort, final int rmiPort) {
    ArgumentNotValid.checkNotNullOrEmpty(localHostName, "String localHostName");
    ArgumentNotValid.checkNotNegative(jmxPort, "int jmxPort");
    ArgumentNotValid.checkNotNegative(rmiPort, "int rmiPort");
    if (registryTimer != null) {
        registryTimer.cancel();
    }
    registryTimer = new Timer("Monitor-registry-client", true);
    TimerTask timerTask = new TimerTask() {
        /** The action to be performed by this timer task. */
        public void run() {
            JMSConnectionFactory.getInstance().send(new RegisterHostMessage(localHostName, jmxPort, rmiPort));
            log.trace("Registering this client for monitoring," + " using hostname '" + localHostName
                    + "' and JMX/RMI ports " + jmxPort + "/" + rmiPort);
        }
    };

    long reregisterDelay = Settings.getLong(MonitorSettings.DEFAULT_REREGISTER_DELAY);
    try {
        reregisterDelay = Long.parseLong(Settings.get(CommonSettings.MONITOR_REGISTRY_CLIENT_REREGISTERDELAY));
    } catch (NumberFormatException e1) {
        log.warn("Couldn't parse setting " + CommonSettings.MONITOR_REGISTRY_CLIENT_REREGISTERDELAY
                + ". Only numbers are allowed. Using defaultvalue " + MonitorSettings.DEFAULT_REREGISTER_DELAY);
    } catch (NetarkivetException e2) {
        log.warn("Couldn't find setting " + CommonSettings.MONITOR_REGISTRY_CLIENT_REREGISTERDELAY
                + ". Using defaultvalue " + MonitorSettings.DEFAULT_REREGISTER_DELAY);
    }

    log.info("Registering this client for monitoring every " + reregisterDelay + " minutes, using hostname '"
            + localHostName + "' and JMX/RMI ports " + jmxPort + "/" + rmiPort);
    registryTimer.scheduleAtFixedRate(timerTask, NOW, reregisterDelay * MINUTE_IN_MILLISECONDS);
}

From source file:com.purplefrog.glitchclocka.LearningReadout.java

public synchronized void ensureTimerRunning() {
    if (timer != null)
        return;//w w  w.  j av a 2 s  .  c  o m

    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            updateProgressTimeBar();
        }
    };
    timer = new Timer();
    timer.scheduleAtFixedRate(timerTask, 0, 10000);
}