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:net.hardisonbrewing.signingserver.SigservPushApplication.java

private void startRegisterServTask() {

    cancelRegisterServTask();/*from   ww  w. ja va2s .c o m*/

    Timer timer = new Timer();
    registerServ = new RegisterServTimerTask();
    timer.schedule(registerServ, 0, Dates.DAY);
}

From source file:password.pwm.util.localdb.LocalDBUtility.java

public void exportLocalDB(final OutputStream outputStream, final Appendable debugOutput,
        final boolean showLineCount) throws PwmOperationalException, IOException {
    if (outputStream == null) {
        throw new PwmOperationalException(PwmError.ERROR_UNKNOWN,
                "outputFileStream for exportLocalDB cannot be null");
    }/*from  ww  w  .  ja v  a 2s. co  m*/

    final int totalLines;
    if (showLineCount) {
        writeStringToOut(debugOutput, "counting records in LocalDB...");
        exportLineCounter = 0;
        for (final LocalDB.DB loopDB : LocalDB.DB.values()) {
            if (loopDB.isBackup()) {
                exportLineCounter += localDB.size(loopDB);
            }
        }
        totalLines = exportLineCounter;
        writeStringToOut(debugOutput, " total lines: " + totalLines);
    } else {
        totalLines = 0;
    }
    exportLineCounter = 0;

    writeStringToOut(debugOutput, "export beginning");
    final long startTime = System.currentTimeMillis();
    final Timer statTimer = new Timer(true);
    statTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            if (showLineCount) {
                final float percentComplete = (float) exportLineCounter / (float) totalLines;
                final String percentStr = DecimalFormat.getPercentInstance().format(percentComplete);
                writeStringToOut(debugOutput,
                        "exported " + exportLineCounter + " records, " + percentStr + " complete");
            } else {
                writeStringToOut(debugOutput, "exported " + exportLineCounter + " records");
            }
        }
    }, 30 * 1000, 30 * 1000);

    try (CSVPrinter csvPrinter = JavaHelper
            .makeCsvPrinter(new GZIPOutputStream(outputStream, GZIP_BUFFER_SIZE))) {
        csvPrinter.printComment(PwmConstants.PWM_APP_NAME + " " + PwmConstants.SERVLET_VERSION
                + " LocalDB export on " + JavaHelper.toIsoDate(new Date()));
        for (final LocalDB.DB loopDB : LocalDB.DB.values()) {
            if (loopDB.isBackup()) {
                csvPrinter.printComment("Export of " + loopDB.toString());
                final LocalDB.LocalDBIterator<String> localDBIterator = localDB.iterator(loopDB);
                try {
                    while (localDBIterator.hasNext()) {
                        final String key = localDBIterator.next();
                        final String value = localDB.get(loopDB, key);
                        csvPrinter.printRecord(loopDB.toString(), key, value);
                        exportLineCounter++;
                    }
                } finally {
                    localDBIterator.close();
                }
                csvPrinter.flush();
            }
        }
        csvPrinter.printComment("export completed at " + JavaHelper.toIsoDate(new Date()));
    } catch (IOException e) {
        writeStringToOut(debugOutput, "IO error during localDB export: " + e.getMessage());
    } finally {
        statTimer.cancel();
    }

    writeStringToOut(debugOutput, "export complete, exported " + exportLineCounter + " records in "
            + TimeDuration.fromCurrent(startTime).asLongString());
}

From source file:com.quadmeup.smartporttelemetrer.activity.RawDataActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_raw_data);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//w  w w.  j av a2 s. c om

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null)
                    .show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    sensorList = (ListView) findViewById(R.id.sensor_list);
    listAdapter = new RawDataListAdapter(this);
    sensorList.setAdapter(listAdapter);

    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            updateUI();
        }
    };
    timer.schedule(doAsynchronousTask, 0, 200); //execute in every 50000 ms
}

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

private void startNetworkRequiredTask() {

    cancelNetworkRequiredTask();/*from  ww  w. j  a va 2s  .  co m*/

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

From source file:org.mousephenotype.dcc.crawler.TheApplication.java

private void run() {
    if (periodicDelayInHours > 0) {
        Timer timer = new Timer();
        timer.schedule(processInitiator, 0L, periodicDelayInHours * HOUR_TO_MILLISECS);
    } else {/*from w  w w  .  j  a  v a2 s . c  o  m*/
        processInitiator.run();
        if (requiresReport) {
            sendReport();
        }
        LOGGER.info("Application will now exit...");
    }
}

From source file:org.jitsi.meet.test.PSNRTest.java

/**
 * A test where we read some configurations or fallback to default values
 * and we expect a conference to be already established (by SetupConference)
 * and we keep checking whether this is still the case, and if something
 * is not working we fail.//from  ww w. ja v a  2  s  . com
 */
public void testPSNR() {
    File inputFrameDir = new File(INPUT_FRAME_DIR);
    if (!inputFrameDir.exists()) {
        // Skip the PSNR tests because we don't have any PSNR
        // resources.
        return;
    }
    // Create the output directory for captured frames.
    File outputFrameDir = new File(OUTPUT_FRAME_DIR);
    if (!outputFrameDir.exists()) {
        outputFrameDir.mkdirs();
    }

    String timeToRunInMin = System.getProperty("psnr.duration");

    // default is 1 minute
    if (timeToRunInMin == null || timeToRunInMin.length() == 0)
        timeToRunInMin = "1";

    final int minutesToRun = Integer.valueOf(timeToRunInMin);

    final CountDownLatch waitSignal = new CountDownLatch(1);

    // execute every 1 sec.
    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        long lastRun = System.currentTimeMillis();

        int millsToRun = minutesToRun * 60 * 1000;

        CountDownLatch ownerDownloadSignal = new CountDownLatch(3);
        CountDownLatch secondPDownloadSignal = new CountDownLatch(3);

        @Override
        public void run() {
            try {
                System.err.println("Checking at " + new Date() + " / to finish: " + millsToRun + " ms.");

                if (!ConferenceFixture.isIceConnected(ConferenceFixture.getOwner())) {
                    assertAndQuit("Owner ice is not connected.");
                    return;
                }

                if (!ConferenceFixture.isInMuc(ConferenceFixture.getOwner())) {
                    assertAndQuit("Owner is not in the muc.");
                    return;
                }

                if (!ConferenceFixture.isIceConnected(ConferenceFixture.getSecondParticipant())) {
                    assertAndQuit("Second participant ice is not connected.");
                    return;
                }

                if (!ConferenceFixture.isInMuc(ConferenceFixture.getSecondParticipant())) {
                    assertAndQuit("The second participant is not in the muc.");
                    return;
                }

                long downloadOwner = ConferenceFixture.getDownloadBitrate(ConferenceFixture.getOwner());
                long downloadParticipant = ConferenceFixture
                        .getDownloadBitrate(ConferenceFixture.getSecondParticipant());

                if (downloadOwner <= 0) {
                    System.err.println("Owner no download bitrate");
                    ownerDownloadSignal.countDown();
                } else
                    ownerDownloadSignal = new CountDownLatch(3);

                if (ownerDownloadSignal.getCount() <= 0) {
                    assertAndQuit("Owner download bitrate less than 0");
                    return;
                }

                if (downloadParticipant <= 0) {
                    System.err.println("Second participant no download bitrate");
                    secondPDownloadSignal.countDown();
                } else
                    secondPDownloadSignal = new CountDownLatch(3);

                if (secondPDownloadSignal.getCount() <= 0) {
                    assertAndQuit("Second participant download rate less than 0");
                    return;
                }

                if (!ConferenceFixture.isXmppConnected(ConferenceFixture.getOwner())) {
                    assertAndQuit("Owner xmpp connection is not connected");
                    return;
                }

                if (!ConferenceFixture.isXmppConnected(ConferenceFixture.getSecondParticipant())) {
                    assertAndQuit("The second participant xmpp " + "connection is not connected");
                    return;
                }

                WebDriver driver = ConferenceFixture.getOwner();
                if (driver instanceof JavascriptExecutor) {
                    JavascriptExecutor js = ((JavascriptExecutor) driver);

                    List<WebElement> remoteThumb = driver
                            .findElements(By.xpath("//video[starts-with(@id, 'remoteVideo_')]"));

                    for (WebElement webElement : remoteThumb) {
                        //FIXME This needs to be optimized. We run this
                        // every second. It encodes an image in base64 and
                        // it transfers it over the network (that's how
                        // selenium communicates with the debugger). So this
                        // might work with a few images per second.. But this
                        // will fail miserably if we want to capture 30fps.
                        // The proper solution would be to store the images
                        // in the sandboxed HTML filesystem that modern
                        // browsers provide. And transfer them at the end
                        // of the test. We could follow the same approach
                        // if we want to grab the whole webm/vp8 stream using
                        // the Recorder API.
                        String elmId = webElement.getAttribute("id");
                        Object pngUrl = js.executeScript("var video = document.getElementById(\"" + elmId
                                + "\");" + "var canvasId = 'canvas-capture';"
                                + "var canvas = document.getElementById(canvasId);" + "if (canvas == null) {"
                                + "    canvas = document.createElement('canvas');" + "    canvas.id = canvasId;"
                                + "    document.body.appendChild(canvas);" + "}"
                                + "canvas.width = video.videoWidth;" + "canvas.height = video.videoHeight;"
                                + "var ctx = canvas.getContext('2d');" + "ctx.drawImage(video, 0, 0);"
                                + "return canvas.toDataURL(\"image/png\");");

                        // Parse the URI to get only the base64 part
                        String strBase64 = pngUrl.toString().substring("data:image/png;base64,".length());

                        // Convert it to binary
                        // Java 8 has a Base64 class.
                        byte[] data = org.apache.commons.codec.binary.Base64.decodeBase64(strBase64);

                        try (OutputStream stream = new FileOutputStream(
                                OUTPUT_FRAME_DIR + elmId + "-" + lastRun + ".png")) {
                            stream.write(data);
                        }
                    }
                }

                long currentTime = System.currentTimeMillis();
                millsToRun -= (currentTime - lastRun);
                lastRun = currentTime;

                if (millsToRun <= 0) {
                    timer.cancel();
                }
            } catch (Exception e) {
                e.printStackTrace();

                assertAndQuit("Unexpected error occurred.");
            }
        }

        /**
         * Clears what is needed and lowers the assert countdown.
         * @param msg
         */
        private void assertAndQuit(String msg) {
            System.err.println(msg);
            waitSignal.countDown();
            timer.cancel();
        }

    }, /* delay */ 1000, /* period */ 1000);

    try {
        waitSignal.await(minutesToRun, TimeUnit.MINUTES);

        if (waitSignal.getCount() == 0)
            assertTrue("A problem with the conf occurred", false);
        else {
            Runtime rt = Runtime.getRuntime();
            String[] commands = { PSNR_SCRIPT, OUTPUT_FRAME_DIR, INPUT_FRAME_DIR, RESIZED_FRAME_DIR };
            Process proc = rt.exec(commands);

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

            // read the output from the command
            String s = null;
            while ((s = stdInput.readLine()) != null) {
                assertTrue(s == null || Float.parseFloat(s.split(" ")[1]) > MIN_PSNR);
            }

            // read any errors from the attempted command
            while ((s = stdError.readLine()) != null) {
                System.err.println(s);
            }
        }
    } catch (Exception e) {
        assertTrue("An error occurred", false);
    }
}

From source file:EventDispatchThreadHangMonitor.java

/**
 * Sets up a timer to check for hangs frequently.
 *///  ww w.  j  av a2 s . com
private void initTimer() {
    final long initialDelayMs = 0;
    final boolean isDaemon = true;
    Timer timer = new Timer("EventDispatchThreadHangMonitor", isDaemon);
    timer.schedule(new HangChecker(), initialDelayMs, CHECK_INTERVAL_MS);
}

From source file:org.pentaho.di.ui.core.dialog.Splash.java

protected Splash(Display display, Shell splashShell) throws KettleException {
    log = new LogChannel(Spoon.APP_NAME);

    Rectangle displayBounds = display.getPrimaryMonitor().getBounds();

    // "kettle_splash.png"
    kettle_image = loadAsResource(display, BasePropertyHandler.getProperty("splash_image"));
    // "spoon.ico"
    kettle_icon = loadAsResource(display, BasePropertyHandler.getProperty("splash_icon"));
    // "exclamation.png"
    exclamation_image = loadAsResource(display, BasePropertyHandler.getProperty("exclamation_image"));

    verFont = new Font(display, "Helvetica", 11, SWT.BOLD);
    licFont = new Font(display, "Helvetica", licFontSize, SWT.NORMAL);
    devWarningFont = new Font(display, "Helvetica", 10, SWT.NORMAL);

    // versionWarningBackgroundColor = new Color(display, 255, 253, 213);
    versionWarningBackgroundColor = new Color(display, 255, 255, 255);
    versionWarningForegroundColor = new Color(display, 220, 177, 20);

    splash = splashShell;//  w w w.  j a va2s  . c o  m
    splash.setImage(kettle_icon);

    splash.setText(BaseMessages.getString(PKG, "SplashDialog.Title")); // "Pentaho Data Integration"

    splash.addPaintListener(new PaintListener() {
        public void paintControl(PaintEvent e) {
            StringBuilder sb = new StringBuilder();
            String line = null;

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(Splash.class.getClassLoader()
                        .getResourceAsStream("org/pentaho/di/ui/core/dialog/license/license.txt")));

                while ((line = reader.readLine()) != null) {
                    sb.append(line + System.getProperty("line.separator"));
                }
            } catch (Exception ex) {
                sb.append("");
                log.logError(BaseMessages.getString(PKG, "SplashDialog.LicenseTextNotFound"), ex);
            }
            Calendar cal = Calendar.getInstance();
            String licenseText = String.format(sb.toString(), cal);
            e.gc.drawImage(kettle_image, 0, 0);

            String fullVersionText = BaseMessages.getString(PKG, "SplashDialog.Version");
            String buildVersion = BuildVersion.getInstance().getVersion();
            if (StringUtils.ordinalIndexOf(buildVersion, ".", 2) > 0) {
                fullVersionText = fullVersionText + " "
                        + buildVersion.substring(0, StringUtils.ordinalIndexOf(buildVersion, ".", 2));
            } else {
                fullVersionText = fullVersionText + " " + buildVersion;
            }
            e.gc.setFont(verFont);
            e.gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
            e.gc.drawText(fullVersionText, 290, 205, true);

            String inputStringDate = BuildVersion.getInstance().getBuildDate();
            String outputStringDate = "";
            SimpleDateFormat inputFormat = null;
            SimpleDateFormat outputFormat = null;

            if (inputStringDate.matches("^\\d{4}/\\d{1,2}/\\d{1,2}\\s\\d{1,2}:\\d{2}:\\d{2}.\\d{3}$")) {
                inputFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss.SSS");
            }
            if (inputStringDate.matches("^\\d{4}-\\d{1,2}-\\d{1,2}\\_\\d{1,2}-\\d{2}-\\d{2}$")) {
                inputFormat = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
            }
            if (inputStringDate.matches("^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}.\\d{2}.\\d{2}$")) {
                inputFormat = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss");
            }
            outputFormat = new SimpleDateFormat("MMMM d, yyyy hh:mm:ss");
            try {
                if (inputFormat != null) {
                    Date date = inputFormat.parse(inputStringDate);
                    outputStringDate = outputFormat.format(date);
                } else {
                    // If date isn't correspond to formats above just show date in origin format
                    outputStringDate = inputStringDate;
                }
            } catch (ParseException pe) {
                // Just show date in origin format
                outputStringDate = inputStringDate;
            }

            // try using the desired font size for the license text
            e.gc.setFont(licFont);
            e.gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));

            // if the text will not fit the allowed space
            while (!willLicenseTextFit(licenseText, e.gc)) {
                licFontSize--;
                if (licFont != null) {
                    licFont.dispose();
                }
                licFont = new Font(e.display, "Helvetica", licFontSize, SWT.NORMAL);
                e.gc.setFont(licFont);
            }

            e.gc.drawText(licenseText, 290, 275, true);

            String version = buildVersion;
            // If this is a Milestone or RC release, warn the user
            if (Const.RELEASE.equals(Const.ReleaseType.MILESTONE)) {
                version = BaseMessages.getString(PKG, "SplashDialog.DeveloperRelease") + " - " + version;
                drawVersionWarning(e);
            } else if (Const.RELEASE.equals(Const.ReleaseType.RELEASE_CANDIDATE)) {
                version = BaseMessages.getString(PKG, "SplashDialog.ReleaseCandidate") + " - " + version;
            } else if (Const.RELEASE.equals(Const.ReleaseType.PREVIEW)) {
                version = BaseMessages.getString(PKG, "SplashDialog.PreviewRelease") + " - " + version;
            } else if (Const.RELEASE.equals(Const.ReleaseType.GA)) {
                version = BaseMessages.getString(PKG, "SplashDialog.GA") + " - " + version;
            }
            String buildDate = BaseMessages.getString(PKG, "SplashDialog.BuildDate") + " " + outputStringDate;
            // use the same font/size as the license text
            e.gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
            e.gc.drawText(version, 290, 235, true);
            e.gc.drawText(buildDate, 290, 250, true);
        }
    });

    splash.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent arg0) {
            kettle_image.dispose();
            kettle_icon.dispose();
            exclamation_image.dispose();
            verFont.dispose();
            licFont.dispose();
            devWarningFont.dispose();
            versionWarningForegroundColor.dispose();
            versionWarningBackgroundColor.dispose();
        }
    });
    Rectangle bounds = kettle_image.getBounds();
    int x = (displayBounds.width - bounds.width) / 2;
    int y = (displayBounds.height - bounds.height) / 2;

    splash.setSize(bounds.width, bounds.height);
    splash.setLocation(x, y);

    splash.open();

    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            try {
                splash.redraw();
                LogChannel.UI.logBasic("Redraw!");
            } catch (Throwable e) {
                // ignore.
            }
        }
    };
    final Timer timer = new Timer();
    timer.schedule(timerTask, 0, 100);

    splash.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent arg0) {
            timer.cancel();
        }
    });
}

From source file:org.alfresco.bm.test.Test.java

@Override
public void start() throws Exception {
    initNetworkDetails();/*  w w w. j  ava  2  s  .c o  m*/

    // The core BM Server application does NOT drive anything
    boolean isDriver = !release.toLowerCase().startsWith("alfresco-benchmark-server-");
    if (isDriver) {
        // Ensure that there is a representation of the test in the DB
        initTestDefaults();

        // Register this driver
        registerDriver();

        // Store driver details
        refreshRegistrationTask.run();
        // Make sure we keep it refreshed
        Timer timer = new Timer("TestDriverPing-" + release + "-" + schema, true);
        timer.schedule(refreshRegistrationTask, 0L, TestDriverPingTask.PING_TIMEOUT / 2);

        // Create monitors for all test runs of interest
        testRunPingTask.run();
        // Keep it refreshed
        timer = new Timer("TestRunPing-" + release + "-" + schema, true);
        timer.schedule(testRunPingTask, testRunMonitorPeriod, testRunMonitorPeriod);
    } else {
        logger.debug("Not registering driver details: " + release + ", " + schema + ", " + systemCapabilities);
    }
}

From source file:com.eutectoid.dosomething.picker.PlacePickerFragment.java

private Timer createSearchTextTimer() {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override/*ww  w.ja  v a  2  s  . c om*/
        public void run() {
            onSearchTextTimerTriggered();
        }
    }, 0, searchTextTimerDelayInMilliseconds);

    return timer;
}