Example usage for java.util Timer cancel

List of usage examples for java.util Timer cancel

Introduction

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

Prototype

public void cancel() 

Source Link

Document

Terminates this timer, discarding any currently scheduled tasks.

Usage

From source file:kieker.tools.resourceMonitor.ResourceMonitor.java

@Override
protected boolean performTask() {
    LOG.info(this.toString());

    final CountDownLatch cdl = new CountDownLatch(1);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override/*from w ww  . ja  va 2s  .  com*/
        public void run() {
            cdl.countDown();
        }
    });

    final Configuration controllerConfiguration;
    if (this.monitoringConfigurationFile != null) {
        controllerConfiguration = ConfigurationFactory
                .createConfigurationFromFile(this.monitoringConfigurationFile);
    } else {
        controllerConfiguration = ConfigurationFactory.createSingletonConfiguration();
    }
    this.monitoringController = MonitoringController.createInstance(controllerConfiguration);

    this.initSensors();
    LOG.info("Monitoring started");

    if (this.duration >= 0) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                cdl.countDown();
                timer.cancel();
            }
        }, TimeUnit.MILLISECONDS.convert(this.duration, this.durationUnit));
        LOG.info("Waiting for " + this.duration + " " + this.durationUnit + " timeout...");
    }

    try {
        LOG.info("Press Ctrl+c to terminate");
        cdl.await();
    } catch (final InterruptedException ex) {
        LOG.warn("The monitoring has been interrupted", ex);
        return false;
    } finally {
        LOG.info("Monitoring terminated");
    }

    return true;
}

From source file:org.graylog.plugins.backup.strategy.AbstractMongoBackupStrategy.java

protected synchronized void processCommand(List<String> command) throws Exception {
    //need to find a a smart way to manage processBuilder

    ProcessBuilder pb = new ProcessBuilder(command);
    pb.redirectErrorStream(true);/*  w  w  w .j a  va  2s.c  om*/
    Process p = pb.start();

    Timer timeOut = new Timer();
    timeOut.schedule(new TimerTask() {
        @Override
        public void run() {
            if (p.isAlive()) {
                LOG.warn("restore process take more than 15 sec I'll destroy it");
                p.destroy();
            }
        }

        //this parameter need to be configurable

    }, 15000);

    p.waitFor();
    timeOut.cancel();

}

From source file:deincraftlauncher.IO.download.Downloader.java

private void update() {

    System.out.println("downloader update #" + updateNum);
    updateNum++;/*from w ww. ja va  2 s  . co m*/

    if (instance.finished) {
        System.out.println("cancelling updating");
        return;
    }

    onUpdate.call(totalProgress, totalSize, this);

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            //periodic update
            timer.cancel();
            timer.purge();
            update();
        }
    }, updateDelay);

}

From source file:com.predic8.membrane.core.Router.java

private void stopAutoReinitializator() {
    Timer reinitializator2 = reinitializator;
    if (reinitializator2 != null) {
        reinitializator2.cancel();
    }
}

From source file:org.apache.pulsar.functions.runtime.LocalRunner.java

protected static void startLocalRun(org.apache.pulsar.functions.proto.Function.FunctionDetails functionDetails,
        int parallelism, int instanceIdOffset, String brokerServiceUrl, String stateStorageServiceUrl,
        AuthenticationConfig authConfig, String userCodeFile) throws Exception {

    String serviceUrl = DEFAULT_SERVICE_URL;
    if (brokerServiceUrl != null) {
        serviceUrl = brokerServiceUrl;/*from  w w  w. ja v  a2s. c  o  m*/
    }

    try (ProcessRuntimeFactory containerFactory = new ProcessRuntimeFactory(serviceUrl, stateStorageServiceUrl,
            authConfig, null, /* java instance jar file */
            null, /* python instance file */
            null, /* log directory */
            null, /* extra dependencies dir */
            new DefaultSecretsProviderConfigurator())) {
        List<RuntimeSpawner> spawners = new LinkedList<>();
        for (int i = 0; i < parallelism; ++i) {
            InstanceConfig instanceConfig = new InstanceConfig();
            instanceConfig.setFunctionDetails(functionDetails);
            // TODO: correctly implement function version and id
            instanceConfig.setFunctionVersion(UUID.randomUUID().toString());
            instanceConfig.setFunctionId(UUID.randomUUID().toString());
            instanceConfig.setInstanceId(i + instanceIdOffset);
            instanceConfig.setMaxBufferedTuples(1024);
            instanceConfig.setPort(Utils.findAvailablePort());
            instanceConfig.setClusterName("local");
            RuntimeSpawner runtimeSpawner = new RuntimeSpawner(instanceConfig, userCodeFile, null,
                    containerFactory, 30000);
            spawners.add(runtimeSpawner);
            runtimeSpawner.start();
        }
        java.lang.Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                log.info("Shutting down the localrun runtimeSpawner ...");
                for (RuntimeSpawner spawner : spawners) {
                    spawner.close();
                }
            }
        });
        Timer statusCheckTimer = new Timer();
        statusCheckTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                CompletableFuture<String>[] futures = new CompletableFuture[spawners.size()];
                int index = 0;
                for (RuntimeSpawner spawner : spawners) {
                    futures[index] = spawner.getFunctionStatusAsJson(index);
                    index++;
                }
                try {
                    CompletableFuture.allOf(futures).get(5, TimeUnit.SECONDS);
                    for (index = 0; index < futures.length; ++index) {
                        String json = futures[index].get();
                        Gson gson = new GsonBuilder().setPrettyPrinting().create();
                        log.info(gson.toJson(new JsonParser().parse(json)));
                    }
                } catch (Exception ex) {
                    log.error("Could not get status from all local instances");
                }
            }
        }, 30000, 30000);
        java.lang.Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                statusCheckTimer.cancel();
            }
        });
        for (RuntimeSpawner spawner : spawners) {
            spawner.join();
            log.info("RuntimeSpawner quit because of", spawner.getRuntime().getDeathException());
        }

    }
}

From source file:org.texai.torrent.TrackerTest.java

/**
 * Test of bit torrent tracker.//from ww  w  .  j av a2 s.  c  o  m
 */
@Test
public void testTracker() {
    LOGGER.info("tracker");

    // configure the HTTP request handler by registering the tracker
    final HTTPRequestHandler httpRequestHandler = HTTPRequestHandler.getInstance();
    final Tracker tracker = new Tracker();
    tracker.addInfoHash(new String((new URLCodec()).encode(INFO_HASH)));
    httpRequestHandler.register(tracker);

    // configure the server channel pipeline factory
    final AbstractBitTorrentHandlerFactory bitTorrentHandlerFactory = new MockBitTorrentHandlerFactory();
    final AbstractHTTPRequestHandlerFactory httpRequestHandlerFactory = new HTTPRequestHandlerFactory();
    final X509SecurityInfo x509SecurityInfo = KeyStoreTestUtils.getServerX509SecurityInfo();
    final ChannelPipelineFactory channelPipelineFactory = new PortUnificationChannelPipelineFactory(null, // albusHCNMessageHandlerFactory,
            bitTorrentHandlerFactory, httpRequestHandlerFactory, x509SecurityInfo);

    // configure the server
    final ServerBootstrap serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
            Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    assertEquals("{}", serverBootstrap.getOptions().toString());
    serverBootstrap.setPipelineFactory(channelPipelineFactory);

    // bind and start to accept incoming connections
    serverBootstrap.bind(new InetSocketAddress("localhost", SERVER_PORT));

    // test tracker client
    httpClient();

    final Timer timer = new Timer();
    timer.schedule(new ShutdownTimerTask(), 5000);

    // shut down executor threads to exit
    LOGGER.info("releasing server resources");
    serverBootstrap.releaseExternalResources();
    timer.cancel();
}

From source file:streamcruncher.innards.db.DatabaseInterface.java

private void setupLastStandingConnection() throws SQLException {
    if (privateVolatileInstance == true) {
        sentinelConnection = createConnection();
        sentinelConnection.setAutoCommit(false);

        sentinelConnectionKeeper = new Timer("SentinelConnectionKeeper", true);

        /*//  w  w w .jav  a 2  s  .c o  m
         * Keep checking periodically and ensure that the sentinelConnection
         * does not timeout.
         */
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                boolean isClosed = false;
                Throwable error = null;
                try {
                    isClosed = DatabaseInterface.this.sentinelConnection.isClosed();
                } catch (SQLException e1) {
                    error = e1;
                }

                if (error != null || isClosed) {
                    Logger logger = Registry.getImplFor(LoggerManager.class)
                            .getLogger(DatabaseInterface.class.getName());
                    String msg = "The Private/Volatile Database instance may be at"
                            + " risk, because the sentinel Connection has been lost.";
                    if (error == null) {
                        logger.log(Level.SEVERE, msg);
                    } else {
                        logger.log(Level.SEVERE, msg, error);
                    }

                    SystemEventBus bus = Registry.getImplFor(SystemEventBus.class);
                    SystemEvent event = new SystemEvent(DatabaseInterface.class.getName(),
                            "Sentinel Connection Lost", error, Priority.SEVERE);
                    bus.submit(event);

                    // -----------

                    // Try and create a new one.
                    try {
                        Timer oldTimer = DatabaseInterface.this.sentinelConnectionKeeper;

                        DatabaseInterface.this.setupLastStandingConnection();

                        // Cancel this old timer.
                        oldTimer.cancel();
                    } catch (SQLException e) {
                        logger.log(Level.SEVERE,
                                "An error occurred while the sentinel" + " Connection was being re-created.",
                                e);

                        event = new SystemEvent(DatabaseInterface.class.getName(),
                                "Sentinel Connection Re-creation Error", null, Priority.SEVERE);
                        bus.submit(event);

                        return;
                    }
                }

                // ------------

                try {
                    DatabaseInterface.this.sentinelConnection.commit();
                } catch (SQLException e) {
                    Logger logger = Registry.getImplFor(LoggerManager.class)
                            .getLogger(DatabaseInterface.class.getName());
                    logger.log(Level.SEVERE,
                            "An error occurred while the sentinel" + " Connection was pinging the Database.",
                            e);

                    SystemEventBus bus = Registry.getImplFor(SystemEventBus.class);
                    SystemEvent event = new SystemEvent(DatabaseInterface.class.getName(),
                            "Sentinel Connection Ping Error", null, Priority.SEVERE);
                    bus.submit(event);
                }
            }
        };
        sentinelConnectionKeeper.scheduleAtFixedRate(timerTask, 10 * 1000, 30 * 1000);
    }
}

From source file:org.openmrs.scheduler.timer.TimerSchedulerServiceImpl.java

/**
 * Convenience method to stop all tasks in the {@link #taskDefinitionTimerMap}
 *//*w  w  w  .  j a va2  s  .  c o  m*/
private void cancelAllTimers() {
    for (Timer timer : taskDefinitionTimerMap.values()) {
        timer.cancel();
    }
}

From source file:com.fatelon.partyphotobooth.kiosk.KioskService.java

/**
 * Starts a timer to launch and relaunch the {@link KioskActivity} in order to keep it in foreground until Kiosk
 * mode is disabled./*w w w . j  av  a  2s.  c o  m*/
 *
 * @param context the {@link Context}.
 */
private void startKioskLauncher(final Context context) {
    final KioskModeHelper kioskModeHelper = new KioskModeHelper(context);
    final Intent intent = new Intent(context, KioskActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    // Start timer to launch and relaunch the KioskActivity.
    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            if (kioskModeHelper.isEnabled()) {
                if (!KioskActivity.sIsInForeground) {
                    // Send Intent to start KioskActivity.
                    startActivity(intent);
                }
            } else {
                // Stop the timer and the KioskService.
                timer.cancel();
                stopSelf();
            }
        }
    }, 0, KIOSK_ACTIVITY_RELAUNCH_PERIOD);
}

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  va2 s. 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();
        }
    });
}