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:org.pepstock.jem.node.persistence.RecoveryManager.java

/**
 * Creates the manager scheduling the timer to check
 * if the database is up & running/*w ww.  j  av a 2 s  .  c  o  m*/
 */
private RecoveryManager() {
    // gets the name of the class as name of the timer
    String className = FilenameUtils.getExtension(this.getClass().getName());
    // schedules the time
    Timer timer = new Timer(className, false);
    timer.schedule(new PersistenceHealthCheck(), 1, 15 * TimeUtils.SECOND);
}

From source file:com.barchart.udt.AppServer.java

private void time() {
    final TimerTask tt = new TimerTask() {

        @Override/* w ww . j a  v a2 s  .c o m*/
        public void run() {
            final long cur = System.currentTimeMillis();
            final long secs = (cur - start) / 1000;
            log.info("Received: " + count / 1024 + " SPEED: " + (count / 1024) / secs + "KB/s");
        }
    };
    final Timer t = new Timer();
    t.schedule(tt, 2000, 2000);
}

From source file:com.cyberlogix.mist6020biometrics.RosterController.java

public void printsListener() {

    long delay = 5 * 1000;
    final long period = 5 * 1000;
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override//ww  w  .  j  ava2 s .  c o  m
        public void run() {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    String b64Print = bio.getImage(rosterImage, rosterPbar, rosterPin, new Stage(), period);
                    System.out.println("Print: " + b64Print);
                    try {
                        if (!b64Print.equalsIgnoreCase("error")) {
                            String url = ServerConnect.STUDENTS_URL + "/verify";
                            ServerConnect sc = new ServerConnect();
                            JSONObject req = new JSONObject();
                            req.put("print", b64Print);
                            ServerResponse msg = sc.processRequest(req.toString(), url,
                                    ServerConnect.METHOD_POST);
                            if (msg.getStatusCode() == 200 || msg.getStatusCode() == 201) {
                                ObjectMapper jackson = new ObjectMapper();
                                Student student = jackson.readValue(
                                        msg.getResponse().getJSONObject("payload").toString(), Student.class);
                                //update table
                                int pos = -1;
                                ObservableList<Student> students = tblRoster.getItems();
                                for (int i = 0; i < students.size(); i++) {
                                    if (students.get(i).getId() == student.getId()) {
                                        System.out.println("Student Matched...");
                                        student.setSignedIn("Present");
                                        students.remove(students.get(i));
                                        pos = i;
                                    }
                                }
                                if (pos >= 0) {
                                    students.add(pos, student);
                                }
                                System.out.println("Students Size: " + students.size());
                                tblRoster.setItems(students);

                                //                                    Dialogs.showConfirmDialog(new Stage(), msg.getResponse().getString("message") + " " + student.getName());
                                alertBox.setText(
                                        msg.getResponse().getString("message") + " " + student.getName());
                                alertBox.setStyle("-fx-text-fill: green; -fx-font-weight: bold;");
                            } else {
                                //                                    Dialogs.showErrorDialog(new Stage(), msg.getResponse().getString("message"), "Error " + msg.getStatusCode(), "Error");
                                alertBox.setText(msg.getResponse().getString("message"));
                                alertBox.setStyle("-fx-text-fill: red; -fx-font-weight: bold;");
                            }
                        }

                    } catch (JSONException | IOException e) {
                        UtilHelper.debugTrace(e);
                    }
                }
            });
        }
    }, delay, period);

}

From source file:org.sonar.server.benchmark.IssueIndexBenchmarkTest.java

private void benchmarkIssueIndexing() {
    LOGGER.info("Indexing issues");
    IssueIterator issues = new IssueIterator(PROJECTS, FILES_PER_PROJECT, ISSUES_PER_FILE);
    ProgressTask progressTask = new ProgressTask(LOGGER, "issues", issues.count());
    Timer timer = new Timer("IssuesIndex");
    timer.schedule(progressTask, ProgressTask.PERIOD_MS, ProgressTask.PERIOD_MS);

    long start = System.currentTimeMillis();
    tester.get(IssueIndexer.class).index(issues);

    timer.cancel();/*from w w  w. j a v a 2 s. c  om*/
    long period = System.currentTimeMillis() - start;
    long throughputPerSecond = 1000 * issues.count.get() / period;
    LOGGER.info(String.format("%d issues indexed in %d ms (%d docs/second)", issues.count.get(), period,
            throughputPerSecond));
    benchmark.expectAround("Throughput to index issues", throughputPerSecond, 6500,
            Benchmark.DEFAULT_ERROR_MARGIN_PERCENTS);

    // be sure that physical files do not evolve during estimation of size
    tester.get(EsClient.class).prepareOptimize("issues").get();
    long dirSize = FileUtils.sizeOfDirectory(tester.getEsServerHolder().getHomeDir());
    LOGGER.info(String.format("ES dir: " + FileUtils.byteCountToDisplaySize(dirSize)));
    benchmark.expectBetween("ES dir size (b)", dirSize, 200L * FileUtils.ONE_MB, 420L * FileUtils.ONE_MB);
}

From source file:ca.blackperl.WordFilterStreamBuilder.java

public void main() {
    // create the twitter search listener
    PhraseListener listener = new PhraseListener(args);

    // Connect to twitter.
    final TwitterStream twitterStream = new TwitterStreamFactory().getInstance();

    // The listener to the twitter connection
    twitterStream.addListener(listener);

    // Build a search configuration
    ArrayList<Long> follow = new ArrayList<Long>();
    ArrayList<String> track = new ArrayList<String>();
    for (String arg : args) {
        if (isNumericalArgument(arg)) {
            for (String id : arg.split(",")) {
                follow.add(Long.parseLong(id));
            }//from w  ww.  j ava2 s  .  com
        } else {
            track.addAll(Arrays.asList(arg.split(",")));
        }
    }
    long[] followArray = new long[follow.size()];
    for (int i = 0; i < follow.size(); i++) {
        followArray[i] = follow.get(i);
    }
    String[] trackArray = track.toArray(new String[track.size()]);

    // filter() method internally creates a thread which manipulates
    // TwitterStream and calls the listener methods continuously.

    // pass the search configuration to the twitter library to start the search
    twitterStream.filter(new FilterQuery(0, followArray, trackArray));

    // Create a timer
    final Timer timer = new Timer();

    // Create a task to run every minute, starting in one minute.
    TimerTask summaryTask = new SummaryTask(listener, timer, twitterStream);
    timer.schedule(summaryTask, TimeToRunInSeconds * 1000, TimeToRunInSeconds * 1000);
}

From source file:org.exist.netedit.NetEditApplet.java

public void init() {

    sessionid = getParameter("sessionid");

    user = new File(System.getProperty("user.home"));
    exist = new File(user, ".eXist");
    etc = new File(exist, "gate");

    String host = getParameter("host");
    if (host != null) {
        etc = new File(etc, host);
    }/*from  w  ww . j av a 2s .  c  om*/

    meta = new File(etc, "meta");
    cache = new File(etc, "cache");

    // Setup HTTP proxy
    String proxyHost = System.getProperty("http.proxyHost");
    if (proxyHost != null && !proxyHost.equals("")) {
        ProxyHost proxy = new ProxyHost(proxyHost, Integer.parseInt(System.getProperty("http.proxyPort")));
        http.getHostConfiguration().setProxyHost(proxy);
    }

    // Detect OS open file command 
    String os = System.getProperty("os.name").toLowerCase();
    if (os.indexOf("windows") != -1 || os.indexOf("nt") != -1) {
        opencmd = "cmd /c \"start %s\"";
    } else if (os.indexOf("mac") != -1) {
        opencmd = "open %s";
    } else {
        opencmd = "xdg-open %s";
    }

    // Load tasks of old applet's sessions
    manager.load();

    // Start main trusted thread
    Timer timer = new Timer();
    timer.schedule(manager, PERIOD, PERIOD);
}

From source file:org.zepan.elasticsearch.river.pinboard.PinboardRiver.java

@java.lang.Override
public void start() {

    logger.info("Starting Pinboard river");
    logger.info("Pinboard index will be refreshed every {} seconds", this.fetchInterval);

    if (!client.admin().indices().prepareExists(indexName).execute().actionGet().exists()) {

        CreateIndexRequestBuilder createIndexRequest = client.admin().indices().prepareCreate(indexName);

        if (settings != null) {
            createIndexRequest.setSettings(settings);
        }//from   www  .  ja  va  2s.c  om
        if (mapping != null) {
            createIndexRequest.addMapping(typeName, mapping);
        }

        createIndexRequest.execute().actionGet();
    }

    Timer timer = new Timer("Printer");
    MyTask t = new MyTask();
    timer.schedule(t, 0, this.fetchInterval * 1000);

}

From source file:org.fatal1t.forexapp.spring.api.adapters.APIStreamingAdapter.java

@Override
public void start() {
    this.session = AppSession.getSession();
    initate();/*from  w  w  w . ja  v  a2s. co  m*/
    try {
        /// Tick data listenener 
        List<String> testSymbols = new ArrayList<>();
        List<String> symbols;
        testSymbols.add("EURUSD");
        testSymbols.add("EURGBP");
        testSymbols.add("EURCZK");
        symbols = loadSymbols();
        final StreamingListener tickListener = new StreamingListener() {
            @Override
            public void receiveTickRecord(STickRecord tickRecord) {
                TickRecord record = new TickRecord(tickRecord.getAsk(), tickRecord.getBid(),
                        tickRecord.getAskVolume(), tickRecord.getBidVolume(), tickRecord.getHigh(),
                        tickRecord.getLow(), tickRecord.getSpreadRaw(), tickRecord.getSpreadTable(),
                        tickRecord.getSymbol(), tickRecord.getQuoteId(), tickRecord.getLevel(),
                        tickRecord.getTimestamp());
                log.info("Async: prijata Tick zprava: " + record.getSymbol());
                connector.sendMessage(record);
            }

            @Override
            public void receiveCandleRecord(SCandleRecord candleRecord) {
                CandleDataRecord record = new CandleDataRecord(candleRecord.getCtm(),
                        candleRecord.getCtmString(), candleRecord.getOpen(), candleRecord.getHigh(),
                        candleRecord.getLow(), candleRecord.getClose(), candleRecord.getVol(),
                        candleRecord.getQuoteId(), candleRecord.getSymbol());
                log.info("Async: prijata Candles zprava: " + record.getSymbol());
                connector.sendMessage(record);
            }

            @Override
            public void receiveBalanceRecord(SBalanceRecord record) {
                BalanceRecord newRecord = new BalanceRecord(record);
                connector.sendMessage(newRecord);
            }

            @Override
            public void receiveNewsRecord(SNewsRecord record) {
                NewsRecord newRecord = new NewsRecord(record);
                connector.sendMessage(newRecord);
            }

            @Override
            public void receiveKeepAliveRecord(SKeepAliveRecord keepAliveRecord) {

            }

            @Override
            public void receiveTradeRecord(STradeRecord record) {
                TradeRecord newRecord = new TradeRecord(record);
                connector.sendMessage(newRecord);
            }
        };
        this.tickConnector.connectStream(tickListener);
        this.tickConnector.subscribePrices(symbols);
        this.tickConnector.subscribeCandles(symbols);
        this.tickConnector.subscribeBalance();
        this.tickConnector.subscribeKeepAlive();
        this.tickConnector.subscribeNews();
        this.tickConnector.subscribeTrades();

        Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    tickConnector.safeExecuteCommand(APICommandFactory.createPingCommand());
                } catch (APICommandConstructionException | APICommunicationException ex) {
                    try {
                        log.error("Problem s konektort, restartuju");
                        tickConnector.close();
                        tickConnector = initConnector();
                        tickConnector.connectStream(tickListener);
                        tickConnector.subscribePrices(symbols);
                        tickConnector.subscribeCandles(symbols);
                        tickConnector.subscribeBalance();
                        tickConnector.subscribeKeepAlive();
                        tickConnector.subscribeNews();
                        tickConnector.subscribeTrades();
                    } catch (IOException | APICommunicationException ex1) {
                        log.fatal(ex1.getStackTrace());

                    }
                }

            }
        }, 300000, 300000);
    } catch (IOException | APICommunicationException ex) {
        ex.printStackTrace();
    }
}

From source file:edu.northwestern.cbits.activitydetector.app.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get detection requester and remover objects
    mDetectionRequester = new DetectionRequester(this);
    mDetectionRemover = new DetectionRemover(this);

    mDetectionRequester.requestUpdates();

    // Set the main layout
    setContentView(R.layout.activity_main);

    nameView = (TextView) this.findViewById(R.id.activity);
    nameView.setText(ActivityRecognitionIntentService.ACTIVITY_NAME);

    Timer myTimer = new Timer();
    myTimer.schedule(new TimerTask() {
        @Override/*from   ww  w.  j  av  a2s.  c o  m*/
        public void run() {
            UpdateGUI();
        }
    }, 0, 1000);

}

From source file:net.hardisonbrewing.signingserver.SigservAutorunApplication.java

private void bootloader() {

    networkReadyListener = new MyNetworkReadyListener();
    addRadioListener(networkReadyListener);
    WLANInfo.addListener(networkReadyListener);

    Timer timer = new Timer();
    networkRequiredTimerTask = new NetworkRequiredTimerTask();
    timer.schedule(networkRequiredTimerTask, Dates.SECOND * 15, Dates.SECOND * 15);
}