Example usage for java.util Timer schedule

List of usage examples for java.util Timer schedule

Introduction

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

Prototype

public void schedule(TimerTask task, Date firstTime, long period) 

Source Link

Document

Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.

Usage

From source file:com.mirth.connect.server.Mirth.java

/**
 * Starts up the server.//from   w  w  w.  ja  v a  2  s  .c  o  m
 * 
 */
public void startup() {
    try {
        ObjectXMLSerializer.getInstance().init(versionProperties.getString("mirth.version"));
    } catch (Exception e) {
    }
    Donkey.getInstance().setSerializer(ObjectXMLSerializer.getInstance());

    configurationController.initializeSecuritySettings();
    configurationController.initializeDatabaseSettings();

    try {
        SqlConfig.getSqlSessionManager().startManagedSession();
        SqlConfig.getSqlSessionManager().getConnection();
    } catch (Exception e) {
        // the getCause is needed since the wrapper exception is from the connection pool
        logger.error(
                "Error establishing connection to database, aborting startup. " + e.getCause().getMessage());
        System.exit(0);
    } finally {
        if (SqlConfig.getSqlSessionManager().isManagedSessionStarted()) {
            SqlConfig.getSqlSessionManager().close();
        }
    }

    extensionController.removePropertiesForUninstalledExtensions();

    try {
        migrationController.migrate();
    } catch (MigrationException e) {
        logger.error("Failed to migrate database schema", e);
        stopDatabase();
        running = false;
        return;
    }

    // MIRTH-3535 disable Quartz update check
    System.setProperty("org.terracotta.quartz.skipUpdateCheck", "true");

    configurationController.migrateKeystore();
    extensionController.setDefaultExtensionStatus();
    extensionController.uninstallExtensions();
    migrationController.migrateExtensions();
    extensionController.initPlugins();
    migrationController.migrateSerializedData();
    userController.resetUserStatus();

    // disable the velocity logging
    Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
            "org.apache.velocity.runtime.log.NullLogSystem");

    eventController.dispatchEvent(new ServerEvent(configurationController.getServerId(), "Server startup"));

    // Start web server before starting the engine in case there is a 
    // problem starting the engine that causes it to hang
    startWebServer();

    configurationController.setStatus(ConfigurationController.STATUS_ENGINE_STARTING);
    startEngine();

    extensionController.startPlugins();

    contextFactoryController.initGlobalContextFactory();

    try {
        alertController.initAlerts();

        configurationController.setStatus(ConfigurationController.STATUS_INITIAL_DEPLOY);

        // Initialize library resources after the above status is set, so that users can login
        try {
            List<LibraryProperties> libraryResources = new ArrayList<LibraryProperties>();
            for (ResourceProperties resource : ObjectXMLSerializer.getInstance()
                    .deserialize(configurationController.getResources(), ResourcePropertiesList.class)
                    .getList()) {
                if (resource instanceof LibraryProperties) {
                    libraryResources.add((LibraryProperties) resource);
                }
            }

            contextFactoryController.updateResources(libraryResources, true);
        } catch (LinkageError e) {
            logger.warn("Unable to initialize library resources.", e);
        } catch (Exception e) {
            logger.warn("Unable to initialize library resources.", e);
        }

        MirthContextFactory contextFactory;
        try {
            contextFactory = contextFactoryController.getGlobalScriptContextFactory();
        } catch (LinkageError e) {
            logger.warn("Unable to initialize global script context factory.", e);
            contextFactory = contextFactoryController.getGlobalContextFactory();
        } catch (Exception e) {
            logger.warn("Unable to initialize global script context factory.", e);
            contextFactory = contextFactoryController.getGlobalContextFactory();
        }
        scriptController.compileGlobalScripts(contextFactory);

        if (configurationController.isStartupDeploy()) {
            engineController.startupDeploy();
        } else {
            logger.info(
                    "Property \"server.startupdeploy\" is disabled. Skipping initial deployment of channels...");
        }
    } catch (Exception e) {
        logger.error(e);
    }

    configurationController.setStatus(ConfigurationController.STATUS_OK);
    printSplashScreen();

    // Send usage stats once a day.
    Timer timer = new Timer();
    timer.schedule(new UsageSenderTask(), 0, ConnectServiceUtil.MILLIS_PER_DAY);
}

From source file:org.openhab.binding.amazonechocontrol.internal.WebSocketConnection.java

private void setSession(Session session) {
    this.session = session;
    logger.debug("Web Socket session started");
    Timer pingTimer = new Timer();
    this.pingTimer = pingTimer;
    pingTimer.schedule(new TimerTask() {

        @Override/*from  w  w  w.  ja v a 2 s .  com*/
        public void run() {
            listener.sendPing();
        }
    }, 180000, 180000);
}

From source file:MonitorSaurausRex.MainMenu.java

public boolean MonitorDirectory() {

    Path directory = Paths.get("C:/Users/" + user + "/Documents/");
    try {//from   ww w.  j  a  v  a 2  s  . co  m
        WatchService fileSystemWatchService = FileSystems.getDefault().newWatchService();
        WatchKey watchKey = directory.register(fileSystemWatchService, StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

        testTimer = new TimerTask() {

            @Override
            public void run() {
                checkPause = true;
                test = changeCheck();

                if (test) {
                    testTimer.cancel();
                    System.out.println("Quaritnen sucsessfully activates");
                }
            }

        };

        Timer timer = new Timer();
        timer.schedule(testTimer, 0, 1000);
        while (true) {
            WatchKey watchKeyActual = fileSystemWatchService.take();
            for (WatchEvent<?> event : watchKeyActual.pollEvents()) {

                WatchEvent.Kind<?> eventKind = event.kind();

                if (eventKind == StandardWatchEventKinds.OVERFLOW) {
                    continue;
                }

                WatchEvent<Path> eventPath = (WatchEvent<Path>) event;
                Path fileName = eventPath.context();

                //timerCheck(); ????? 
                //http://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java
                //  boolean test = false;
                if (checkPause == false) {
                    checkPause = true;
                } else {
                    ChangeCounter++;
                    System.out.println("Event " + eventKind + " occurred on " + fileName);
                }
                if (test)
                    break;
            }
            boolean isReset = watchKeyActual.reset();
            if (!isReset || test) {
                break;
            }
        }

    } catch (IOException | InterruptedException ioe) {
    }

    return true; /// EXIT METHOD
}

From source file:com.norteksoft.cas.web.VerificationCodeValidator.java

private void timeoutTimer() {
    Timer timer = new Timer("login-info-timer", true);
    TimerTask task = new TimerTask() {
        public void run() {
            try {
                timeoutLoginInfo();//from  w w  w . ja v a2 s  .c  o m
            } catch (Exception e) {
                log.debug("validate login info time out error. ", e);
            }
        }
    };
    timer.schedule(task, 30 * 1000l, 30 * 1000l);
}

From source file:org.openhab.binding.knx.internal.connection.KNXConnection.java

@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config != null) {
        sLogger.debug("KNXBinding configuration present. Setting up KNX bus connection.");
        sIp = (String) config.get("ip");

        String readingBusAddrString = (String) config.get("busaddr");
        if (StringUtils.isNotBlank(readingBusAddrString)) {
            sLocalSourceAddr = readingBusAddrString;
        }/*w  ww. ja v  a 2  s  . c  om*/

        String readingIgnLocEv = (String) config.get("ignorelocalevents");
        if (StringUtils.isNotBlank(readingIgnLocEv)) {
            sIgnoreLocalSourceEvents = readingIgnLocEv.equalsIgnoreCase("true");
        }

        String connectionTypeString = (String) config.get("type");
        if (StringUtils.isNotBlank(connectionTypeString)) {
            if ("TUNNEL".equals(connectionTypeString)) {
                sIpConnectionType = KNXNetworkLinkIP.TUNNELING;
            } else if ("ROUTER".equals(connectionTypeString)) {
                sIpConnectionType = KNXNetworkLinkIP.ROUTING;
                if (StringUtils.isBlank(sIp)) {
                    sIp = DEFAULT_MULTICAST_IP;
                }
            } else {
                throw new ConfigurationException("type", "unknown IP connection type '" + connectionTypeString
                        + "'! Known types are either 'TUNNEL' or 'ROUTER'");
            }
        } else {
            sIpConnectionType = KNXNetworkLinkIP.TUNNELING;
        }

        String portConfig = (String) config.get("port");
        if (StringUtils.isNotBlank(portConfig)) {
            sPort = Integer.parseInt(portConfig);
        } else {
            sPort = KNXnetIPConnection.DEFAULT_PORT;
        }

        sLocalIp = (String) config.get("localIp");

        sSerialPort = (String) config.get("serialPort");

        String readingPauseString = (String) config.get("pause");
        if (StringUtils.isNotBlank(readingPauseString)) {
            sReadingPause = Long.parseLong(readingPauseString);
        }

        String responseTimeoutString = (String) config.get("timeout");
        if (StringUtils.isNotBlank(responseTimeoutString)) {
            long timeout = Long.parseLong(responseTimeoutString);
            if (timeout > 0) {
                sResponseTimeout = timeout;
            }
        }

        String readRetriesLimitString = (String) config.get("readRetries");
        if (StringUtils.isNotBlank(readRetriesLimitString)) {
            int readRetries = Integer.parseInt(readRetriesLimitString);
            if (readRetries > 0) {
                sReadRetriesLimit = readRetries;
            }
        }

        String autoReconnectPeriodString = (String) config.get("autoReconnectPeriod");
        if (StringUtils.isNotBlank(autoReconnectPeriodString)) {
            int autoReconnectPeriodValue = Integer.parseInt(autoReconnectPeriodString);
            if (autoReconnectPeriodValue >= 0) {
                sAutoReconnectPeriod = autoReconnectPeriodValue;
            }
        }

        String maxRefreshQueueEntriesString = (String) config.get("maxRefreshQueueEntries");
        if (StringUtils.isNotBlank(maxRefreshQueueEntriesString)) {
            try {
                int maxRefreshQueueEntriesValue = Integer.parseInt(maxRefreshQueueEntriesString);
                if (maxRefreshQueueEntriesValue >= 0) {
                    sMaxRefreshQueueEntries = maxRefreshQueueEntriesValue;
                }
            } catch (NumberFormatException e) {
                sLogger.warn(
                        "Error when trying to read parameter 'maxRefreshQueueEntries' from configuration. '{}' is not a number: using default.",
                        maxRefreshQueueEntriesString);
            }
        }

        String numberOfThreadsString = (String) config.get("numberOfThreads");
        if (StringUtils.isNotBlank(numberOfThreadsString)) {
            try {
                int numberOfThreadsValue = Integer.parseInt(numberOfThreadsString);
                if (numberOfThreadsValue >= 0) {
                    sNumberOfThreads = numberOfThreadsValue;
                }
            } catch (NumberFormatException e) {
                sLogger.warn(
                        "Error when trying to read parameter 'numberOfThreads' from configuration. '{}' is not a number: using default.",
                        numberOfThreadsString);
            }
        }

        String scheduledExecutorServiceShutdownTimeoutString = (String) config
                .get("scheduledExecutorServiceShutdownTimeout");
        if (StringUtils.isNotBlank(scheduledExecutorServiceShutdownTimeoutString)) {
            try {
                int scheduledExecutorServiceShutdownTimeoutValue = Integer
                        .parseInt(scheduledExecutorServiceShutdownTimeoutString);
                if (scheduledExecutorServiceShutdownTimeoutValue >= 0) {
                    sScheduledExecutorServiceShutdownTimeout = scheduledExecutorServiceShutdownTimeoutValue;
                }
            } catch (NumberFormatException e) {
                sLogger.warn(
                        "Error when trying to read parameter 'scheduledExecutorServiceShutdownTimeout' from configuration. '{}' is not a number: using default.",
                        scheduledExecutorServiceShutdownTimeoutString);
            }
        }

        if (sPC == null) {
            sLogger.debug("Not connected yet. Trying to connect.");
            if (!connect()) {
                sLogger.warn("Inital connection to KNX bus failed!");
                if (sAutoReconnectPeriod > 0) {
                    sLogger.info("KNX link will be retried in {} seconds", sAutoReconnectPeriod);
                    final Timer timer = new Timer();
                    TimerTask timerTask = new ConnectTimerTask(timer);
                    timer.schedule(timerTask, sAutoReconnectPeriod * 1000, sAutoReconnectPeriod * 1000);
                }
            } else {
                sLogger.debug("Success: connected.");
            }
        }
    } else {
        sLogger.info(
                "KNXBinding configuration is not present. Please check your configuration file or if not needed remove the KNX addon.");
    }
}

From source file:hspc.submissionsprogram.AppDisplay.java

AppDisplay() {
    this.setTitle("Dominion High School Programming Contest");
    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    this.setResizable(false);

    WindowListener exitListener = new WindowAdapter() {
        @Override//from   ww  w.j  a v a 2  s . c  om
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    };
    this.addWindowListener(exitListener);

    JTabbedPane pane = new JTabbedPane();
    this.add(pane);

    JPanel submitPanel = new JPanel(null);
    submitPanel.setPreferredSize(new Dimension(500, 500));

    UIManager.put("FileChooser.readOnly", true);
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setBounds(0, 0, 500, 350);
    fileChooser.setVisible(true);
    FileNameExtensionFilter javaFilter = new FileNameExtensionFilter("Java files (*.java)", "java");
    fileChooser.setFileFilter(javaFilter);
    fileChooser.setAcceptAllFileFilterUsed(false);
    fileChooser.setControlButtonsAreShown(false);
    submitPanel.add(fileChooser);

    JSeparator separator1 = new JSeparator();
    separator1.setBounds(12, 350, 476, 2);
    separator1.setForeground(new Color(122, 138, 152));
    submitPanel.add(separator1);

    JLabel problemChooserLabel = new JLabel("Problem:");
    problemChooserLabel.setBounds(12, 360, 74, 25);
    submitPanel.add(problemChooserLabel);

    String[] listOfProblems = Main.Configuration.get("problem_names")
            .split(Main.Configuration.get("name_delimiter"));
    JComboBox problems = new JComboBox<>(listOfProblems);
    problems.setBounds(96, 360, 393, 25);
    submitPanel.add(problems);

    JButton submit = new JButton("Submit");
    submit.setBounds(170, 458, 160, 30);
    submit.addActionListener(e -> {
        try {
            File file = fileChooser.getSelectedFile();
            try {
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpPost uploadFile = new HttpPost(Main.Configuration.get("submit_url"));

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.addTextBody("accountID", Main.accountID, ContentType.TEXT_PLAIN);
                builder.addTextBody("problem", String.valueOf(problems.getSelectedItem()),
                        ContentType.TEXT_PLAIN);
                builder.addBinaryBody("submission", file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
                HttpEntity multipart = builder.build();

                uploadFile.setEntity(multipart);

                CloseableHttpResponse response = httpClient.execute(uploadFile);
                HttpEntity responseEntity = response.getEntity();
                String inputLine;
                BufferedReader br = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
                try {
                    if ((inputLine = br.readLine()) != null) {
                        int rowIndex = Integer.parseInt(inputLine);
                        new ResultWatcher(rowIndex);
                    }
                    br.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } catch (NullPointerException ex) {
            JOptionPane.showMessageDialog(this, "No file selected.\nPlease select a java file.", "Error",
                    JOptionPane.WARNING_MESSAGE);
        }
    });
    submitPanel.add(submit);

    JPanel clarificationsPanel = new JPanel(null);
    clarificationsPanel.setPreferredSize(new Dimension(500, 500));

    cList = new JList<>();
    cList.setBounds(12, 12, 476, 200);
    cList.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)),
            BorderFactory.createEmptyBorder(8, 8, 8, 8)));
    cList.setBackground(new Color(254, 254, 255));
    clarificationsPanel.add(cList);

    JButton viewC = new JButton("View");
    viewC.setBounds(12, 224, 232, 25);
    viewC.addActionListener(e -> {
        if (cList.getSelectedIndex() != -1) {
            int id = Integer.parseInt(cList.getSelectedValue().split("\\.")[0]);
            clarificationDatas.stream().filter(data -> data.getId() == id).forEach(
                    data -> new ClarificationDisplay(data.getProblem(), data.getText(), data.getResponse()));
        }
    });
    clarificationsPanel.add(viewC);

    JButton refreshC = new JButton("Refresh");
    refreshC.setBounds(256, 224, 232, 25);
    refreshC.addActionListener(e -> updateCList(true));
    clarificationsPanel.add(refreshC);

    JSeparator separator2 = new JSeparator();
    separator2.setBounds(12, 261, 476, 2);
    separator2.setForeground(new Color(122, 138, 152));
    clarificationsPanel.add(separator2);

    JLabel problemChooserLabelC = new JLabel("Problem:");
    problemChooserLabelC.setBounds(12, 273, 74, 25);
    clarificationsPanel.add(problemChooserLabelC);

    JComboBox problemsC = new JComboBox<>(listOfProblems);
    problemsC.setBounds(96, 273, 393, 25);
    clarificationsPanel.add(problemsC);

    JTextArea textAreaC = new JTextArea();
    textAreaC.setLineWrap(true);
    textAreaC.setWrapStyleWord(true);
    textAreaC.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)),
            BorderFactory.createEmptyBorder(8, 8, 8, 8)));
    textAreaC.setBackground(new Color(254, 254, 255));

    JScrollPane areaScrollPane = new JScrollPane(textAreaC);
    areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    areaScrollPane.setBounds(12, 312, 477, 134);
    clarificationsPanel.add(areaScrollPane);

    JButton submitC = new JButton("Submit Clarification");
    submitC.setBounds(170, 458, 160, 30);
    submitC.addActionListener(e -> {
        if (textAreaC.getText().length() > 2048) {
            JOptionPane.showMessageDialog(this,
                    "Clarification body is too long.\nMaximum of 2048 characters allowed.", "Error",
                    JOptionPane.WARNING_MESSAGE);
        } else if (textAreaC.getText().length() < 20) {
            JOptionPane.showMessageDialog(this,
                    "Clarification body is too short.\nClarifications must be at least 20 characters, but no more than 2048.",
                    "Error", JOptionPane.WARNING_MESSAGE);
        } else {
            Connection conn = null;
            PreparedStatement stmt = null;
            try {
                Class.forName(JDBC_DRIVER);

                conn = DriverManager.getConnection(Main.Configuration.get("jdbc_mysql_address"),
                        Main.Configuration.get("mysql_user"), Main.Configuration.get("mysql_pass"));

                String sql = "INSERT INTO clarifications (team, problem, text) VALUES (?, ?, ?)";
                stmt = conn.prepareStatement(sql);

                stmt.setInt(1, Integer.parseInt(String.valueOf(Main.accountID)));
                stmt.setString(2, String.valueOf(problemsC.getSelectedItem()));
                stmt.setString(3, String.valueOf(textAreaC.getText()));

                textAreaC.setText("");

                stmt.executeUpdate();

                stmt.close();
                conn.close();

                updateCList(false);
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (stmt != null) {
                        stmt.close();
                    }
                } catch (Exception ex2) {
                    ex2.printStackTrace();
                }
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (Exception ex2) {
                    ex2.printStackTrace();
                }
            }
        }
    });
    clarificationsPanel.add(submitC);

    pane.addTab("Submit", submitPanel);
    pane.addTab("Clarifications", clarificationsPanel);

    Timer timer = new Timer();
    TimerTask updateTask = new TimerTask() {
        @Override
        public void run() {
            updateCList(false);
        }
    };
    timer.schedule(updateTask, 10000, 10000);

    updateCList(false);

    this.pack();
    this.setLocationRelativeTo(null);
    this.setVisible(true);
}

From source file:esg.node.components.registry.ESGFRegistry.java

private void startRegistry() {

    //----------------------------------
    log.info("Loading and Initializing...");
    try {/* w  w w.j  a va 2s.c o m*/
        //gleaner.loadMyRegistration();
        gleaner.createMyRegistration().saveRegistration();
    } catch (ESGFRegistryException e) {
        log.warn(e.getMessage());
        gleaner.createMyRegistration();
    }
    Set<Node> loadedNodes = new TreeSet<Node>(nodecomp);
    loadedNodes.addAll(gleaner.getMyRegistration().getNode());

    enqueueESGEvent(new ESGEvent(this,
            new RegistryUpdateDigest(gleaner.toString(), gleaner.getMyChecksum(), loadedNodes),
            "Initializing..."));
    lastDispatchTime.set((new Date()).getTime());
    //----------------------------------

    log.trace("Launching registry timer");
    long delay = Long.parseLong(props.getProperty("registry.initialDelay", "10"));
    final long period = Long.parseLong(props.getProperty("registry.period", "300")); //every 5 mins
    log.debug("registry delay:  " + delay + " sec");
    log.debug("registry period: " + period + " sec");

    Timer timer = new Timer("Quiescence-Reg-Repost-Timer");
    timer.schedule(new TimerTask() {
        public final void run() {
            //If I have not dispatched any information to
            //another peer in "period" seconds then touch the
            //registry (give a new timestamp and thus a new
            //checksum) and send out to share my view with
            //others. The idea here is to only send out your
            //state if you have been inactive for more than
            //"period" time - anecdotal evidence that the
            //network has reached quiescence.  This avoids the
            //case where some node has already pushed their
            //state after quiescense and as such starts the
            //gossip dominoes, which gets here and you send
            //out your state, but without this conditional
            //here, then I would in turn send out my state
            //after the blind elapsing of the period and the
            //do the gossip cascade again... it makes for a
            //noisier network.  So now nodes will deal with
            //one cascade at a time-ish. ;-)

            //Sidebar: There could potentially cause a race condition on
            //lastDispatchTime since longs are not required to
            //be dealt with in an atomic way by the VM, but it
            //won't hurt a thing.
            //-gavin
            Date now = new Date();
            long delta = (now.getTime() - lastDispatchTime.longValue());
            if (delta > (period * 1000)) {
                if (!ESGFRegistry.this.isBusy) {
                    ESGFRegistry.this.isBusy = true;

                    synchronized (gleaner) {
                        //"touch" the registration.xml file (update timestamp via call to createMyRegistration, and resave)
                        log.debug("re-posting registration...");

                        gleaner.saveRegistration();

                        enqueueESGEvent(
                                new ESGEvent(
                                        this, new RegistryUpdateDigest(gleaner.toString(),
                                                gleaner.getMyChecksum(), new HashSet<Node>()),
                                        "Re-Posting Registration State"));
                        lastDispatchTime.set((new Date()).getTime());
                    }
                    ESGFRegistry.this.isBusy = false;
                }
            } else {
                log.debug("Won't re-send state - too soon after last dispatch (quiescence period " + period
                        + "secs, was not reached [" + (delta / 1000) + "secs] elapsed)");
            }
        }
    }, delay * 1000, period * 1000);
}

From source file:org.apache.synapse.core.axis2.SynapseCallbackReceiver.java

/**
 * Create the *single* instance of this class that would be used by all anonymous services
 * used for outgoing messaging./*from   w  w  w  .  java 2 s. c  o  m*/
 * @param synCfg the Synapse configuration
 * @param contextInformation server runtime information
 */
public SynapseCallbackReceiver(SynapseConfiguration synCfg, ServerContextInformation contextInformation) {

    //        callbackStore = Collections.synchronizedMap(new HashMap<String, AxisCallback>());

    // create the Timer object and a TimeoutHandler task
    TimeoutHandler timeoutHandler = new TimeoutHandler(callbackStore, contextInformation);

    Timer timeOutTimer = synCfg.getSynapseTimer();
    long timeoutHandlerInterval = SynapseConfigUtils.getTimeoutHandlerInterval();

    // schedule timeout handler to run every n seconds (n : specified or defaults to 15s)
    timeOutTimer.schedule(timeoutHandler, 0, timeoutHandlerInterval);
}

From source file:esg.node.connection.ESGConnectionManager.java

private void periodicallyPingToPeers() {
    log.trace("Launching ping timer...");
    long delay = Long.parseLong(props.getProperty("conn.ping.initialDelay", "5"));
    long period = Long.parseLong(props.getProperty("conn.ping.period", "30"));
    log.trace("connection ping delay:  " + delay + " sec");
    log.trace("connection ping period: " + period + " sec");

    Timer timer = new Timer("Peer-Sweep-Timer");
    timer.schedule(new TimerTask() {
        public final void run() {
            ESGConnectionManager.this.pingToPeers();
        }/*from   w ww.j  ava2 s .  co  m*/
    }, delay * 1000, period * 1000);
}

From source file:org.pentaho.di.ui.spoon.trans.TransPerfDelegate.java

public void setupContent() {
    // there is a potential infinite loop below if this method
    // is called when the transgraph is not running, so we check
    // early to make sure it won't happen (see PDI-5009)
    if (!transGraph.isRunning() || transGraph.trans == null
            || !transGraph.trans.getTransMeta().isCapturingStepPerformanceSnapShots()) {
        showEmptyGraph();/*from w w  w .  j  a  v a  2 s  .  c  om*/
        return; // TODO: display help text and rerty button
    }

    if (perfComposite.isDisposed()) {
        return;
    }

    // Remove anything on the perf composite, like an empty page message
    //
    for (Control control : perfComposite.getChildren()) {
        if (!control.isDisposed()) {
            control.dispose();
        }
    }

    emptyGraph = false;

    this.title = transGraph.trans.getTransMeta().getName();
    this.timeDifference = transGraph.trans.getTransMeta().getStepPerformanceCapturingDelay();
    this.stepPerformanceSnapShots = transGraph.trans.getStepPerformanceSnapShots();

    // Wait a second for the first data to pour in...
    // TODO: make this wait more elegant...
    //
    while (this.stepPerformanceSnapShots == null || stepPerformanceSnapShots.isEmpty()) {
        this.stepPerformanceSnapShots = transGraph.trans.getStepPerformanceSnapShots();
        try {
            Thread.sleep(100L);
        } catch (InterruptedException e) {
            // Ignore errors
        }
    }

    Set<String> stepsSet = stepPerformanceSnapShots.keySet();
    steps = stepsSet.toArray(new String[stepsSet.size()]);
    Arrays.sort(steps);

    // Display 2 lists with the data types and the steps on the left side.
    // Then put a canvas with the graph on the right side
    //
    Label dataListLabel = new Label(perfComposite, SWT.NONE);
    dataListLabel.setText(BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.Metrics.Label"));
    spoon.props.setLook(dataListLabel);
    FormData fdDataListLabel = new FormData();

    fdDataListLabel.left = new FormAttachment(0, 0);
    fdDataListLabel.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdDataListLabel.top = new FormAttachment(0, Const.MARGIN + 5);
    dataListLabel.setLayoutData(fdDataListLabel);

    dataList = new org.eclipse.swt.widgets.List(perfComposite,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER);
    spoon.props.setLook(dataList);
    dataList.setItems(dataChoices);
    dataList.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {

            // If there are multiple selections here AND there are multiple selections in the steps list, we only take the
            // first step in the selection...
            //
            if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) {
                stepsList.setSelection(stepsList.getSelectionIndices()[0]);
            }

            updateGraph();
        }
    });

    FormData fdDataList = new FormData();
    fdDataList.left = new FormAttachment(0, 0);
    fdDataList.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdDataList.top = new FormAttachment(dataListLabel, Const.MARGIN);
    fdDataList.bottom = new FormAttachment(40, Const.MARGIN);
    dataList.setLayoutData(fdDataList);

    Label stepsListLabel = new Label(perfComposite, SWT.NONE);
    stepsListLabel.setText(BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.Steps.Label"));

    spoon.props.setLook(stepsListLabel);

    FormData fdStepsListLabel = new FormData();
    fdStepsListLabel.left = new FormAttachment(0, 0);
    fdStepsListLabel.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdStepsListLabel.top = new FormAttachment(dataList, Const.MARGIN);
    stepsListLabel.setLayoutData(fdStepsListLabel);

    stepsList = new org.eclipse.swt.widgets.List(perfComposite,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER);
    spoon.props.setLook(stepsList);
    stepsList.setItems(steps);
    stepsList.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {

            // If there are multiple selections here AND there are multiple selections in the data list, we only take the
            // first data item in the selection...
            //
            if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) {
                dataList.setSelection(dataList.getSelectionIndices()[0]);
            }

            updateGraph();
        }
    });
    FormData fdStepsList = new FormData();
    fdStepsList.left = new FormAttachment(0, 0);
    fdStepsList.right = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdStepsList.top = new FormAttachment(stepsListLabel, Const.MARGIN);
    fdStepsList.bottom = new FormAttachment(100, Const.MARGIN);
    stepsList.setLayoutData(fdStepsList);

    canvas = new Canvas(perfComposite, SWT.NONE);
    spoon.props.setLook(canvas);
    FormData fdCanvas = new FormData();
    fdCanvas.left = new FormAttachment(spoon.props.getMiddlePct() / 2, Const.MARGIN);
    fdCanvas.right = new FormAttachment(100, 0);
    fdCanvas.top = new FormAttachment(0, Const.MARGIN);
    fdCanvas.bottom = new FormAttachment(100, 0);
    canvas.setLayoutData(fdCanvas);

    perfComposite.addControlListener(new ControlAdapter() {
        public void controlResized(ControlEvent event) {
            updateGraph();
        }
    });

    perfComposite.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent event) {
            if (image != null) {
                image.dispose();
            }
        }
    });

    canvas.addPaintListener(new PaintListener() {

        public void paintControl(PaintEvent event) {
            if (image != null && !image.isDisposed()) {
                event.gc.drawImage(image, 0, 0);
            }
        }
    });

    // Refresh automatically every 5 seconds as well.
    //
    final Timer timer = new Timer("TransPerfDelegate Timer");
    timer.schedule(new TimerTask() {
        public void run() {
            updateGraph();
        }
    }, 0, 5000);

    // When the tab is closed, we remove the update timer
    //
    transPerfTab.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent arg0) {
            timer.cancel();
        }
    });
}