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:org.openmrs.util.MemoryLeakUtil.java

public static void shutdownMysqlCancellationTimer() {
    try {/*from w  ww . j a  va 2s  .  com*/
        ClassLoader myClassLoader = MemoryLeakUtil.class.getClassLoader();
        Class<?> clazz = Class.forName("com.mysql.jdbc.ConnectionImpl", false, myClassLoader);

        if (!(clazz.getClassLoader() == myClassLoader)) {
            log.info("MySQL ConnectionImpl was loaded with another ClassLoader: (" + clazz.getClassLoader()
                    + "): cancelling anyway");
        } else {
            log.info("MySQL ConnectionImpl was loaded with the WebappClassLoader: cancelling the Timer");
        }

        Field f = clazz.getDeclaredField("cancelTimer");
        f.setAccessible(true);
        Timer timer = (Timer) f.get(null);
        timer.cancel();
        log.info("completed timer cancellation");
    } catch (ClassNotFoundException cnfe) {
        // Ignore
        log.error("Cannot cancel", cnfe);
    } catch (NoSuchFieldException nsfe) {
        // Ignore
        log.error("Cannot cancel", nsfe);
    } catch (SecurityException se) {
        log.info("Failed to shut-down MySQL Statement Cancellation Timer due to a SecurityException", se);
    } catch (IllegalAccessException iae) {
        log.info("Failed to shut-down MySQL Statement Cancellation Timer due to an IllegalAccessException",
                iae);
    }
}

From source file:Main.java

public static Timer setTimeOut(final Runnable runnable, int delayMillis) {
    final Handler handler = new Handler();
    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override/*from   w  w  w . j av a 2 s. c  om*/
        public void run() {
            handler.post(runnable);
            timer.cancel();
        }
    }, delayMillis);
    return timer;
}

From source file:orca.shirako.container.ActorLiveness.java

public static void allStop() {
    Globals.Log.info("Shutting down liveness threads");
    synchronized (timers) {
        noStart = true;// w w  w. j  a  v a2  s  .co  m
        for (Timer t : timers) {
            t.cancel();
        }
        timers.clear();
    }
}

From source file:com.offbynull.portmapper.common.ProcessUtils.java

/**
 * Run a process and dump the stdout stream to a string.
 * @param timeout maximum amount of time the process can take to run
 * @param command command//from  w  w w  .jav  a  2  s .c  o  m
 * @param args arguments
 * @return stdout from the process dumped to a string
 * @throws IOException if the process encounters an error
 * @throws NullPointerException if any arguments are {@code null} or contains {@code null}
 * @throws IllegalArgumentException any numeric argument is negative
 */
public static String runProcessAndDumpOutput(long timeout, String command, String... args) throws IOException {
    Validate.notNull(command);
    Validate.noNullElements(args);
    Validate.inclusiveBetween(0L, Long.MAX_VALUE, timeout);

    String[] pbCmd = new String[args.length + 1];
    pbCmd[0] = command;
    System.arraycopy(args, 0, pbCmd, 1, args.length);

    ProcessBuilder builder = new ProcessBuilder(pbCmd);

    final AtomicBoolean failedFlag = new AtomicBoolean();

    Timer timer = new Timer("Process timeout timer", true);
    Process proc = null;
    try {
        proc = builder.start();

        final Process finalProc = proc;
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                failedFlag.set(true);
                finalProc.destroy();
            }
        }, timeout);

        String ret = IOUtils.toString(proc.getInputStream());
        if (failedFlag.get()) {
            throw new IOException("Process failed");
        }

        return ret;
    } finally {
        if (proc != null) {
            proc.destroy();
        }
        timer.cancel();
        timer.purge();
    }
}

From source file:com.ikon.util.ExecutionUtils.java

/**
 * Execute command line: implementation/*  ww w  . j  a va 2  s .  c o m*/
 */
private static ExecutionResult runCmdImpl(final String cmd[], final long timeout)
        throws SecurityException, InterruptedException, IOException {
    log.debug("runCmdImpl({}, {})", Arrays.toString(cmd), timeout);
    ExecutionResult ret = new ExecutionResult();
    long start = System.currentTimeMillis();
    final ProcessBuilder pb = new ProcessBuilder(cmd);
    final Process process = pb.start();

    Timer t = new Timer("Process Execution Timeout");
    t.schedule(new TimerTask() {
        @Override
        public void run() {
            process.destroy();
            log.warn("Process killed due to timeout.");
            log.warn("CommandLine: {}", Arrays.toString(cmd));
        }
    }, timeout);

    try {
        ret.setStdout(IOUtils.toString(process.getInputStream()));
        ret.setStderr(IOUtils.toString(process.getErrorStream()));
    } catch (IOException e) {
        // Ignore
    }

    process.waitFor();
    t.cancel();
    ret.setExitValue(process.exitValue());

    // Check return code
    if (ret.getExitValue() != 0) {
        log.warn("Abnormal program termination: {}", ret.getExitValue());
        log.warn("CommandLine: {}", Arrays.toString(cmd));
        log.warn("STDERR: {}", ret.getStderr());
    } else {
        log.debug("Normal program termination");
    }

    process.destroy();
    log.debug("Elapse time: {}", FormatUtil.formatSeconds(System.currentTimeMillis() - start));
    return ret;
}

From source file:emperior.Main.java

public static void removeTabbedPaneIcon() {
    final Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override//from  ww  w. j av  a  2  s.c  o m
        public void run() {
            int index = MainFrame.jTabbedPane.getSelectedIndex();
            if (MainFrame.jTabbedPane.getIconAt(index) != null) {
                MainFrame.jTabbedPane.setIconAt(index, null);
                timer.cancel();
            }
        }
    };
    timer.schedule(task, 100, 60000);

}

From source file:org.asimba.util.saml2.metadata.provider.MetadataProviderUtil.java

/**
 * Create a new Filesystem Metadata Provider from the provided filename<br/>
 * An exception is thrown when the file does not exist.
 * /* w  w w.j  a  v a2 s . c  o  m*/
 * @param sId Entity Id that the metadata is being created for 
 * @param sMetadataFile
 * @param oParserPool
 * @param oMPM
 * @return
 * @throws OAException
 */
public static MetadataProvider newFileMetadataProvider(String sId, String sMetadataFile, ParserPool oParserPool,
        IMetadataProviderManager oMPM) throws OAException {
    MetadataProvider oProvider = null;

    // Check whether file exists
    File fMetadata = new File(sMetadataFile);
    if (!fMetadata.exists()) {
        _oLogger.error("The metadata file doesn't exist: " + sMetadataFile);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }

    // Establish dedicated refresh timer:
    String sTimername = "Metadata_File-" + (oMPM == null ? "" : oMPM.getId() + "-") + sId + "-Timer";
    Timer oRefreshTimer = new Timer(sTimername, true);

    oProvider = MetadataProviderUtil.createProviderForFile(sMetadataFile, oParserPool, oRefreshTimer);

    if (oProvider != null) {
        // Start managing it:
        if (oMPM != null) {
            oMPM.setProviderFor(sId, oProvider, oRefreshTimer);
        }
    } else {
        // Unsuccessful creation; clean up created Timer
        oRefreshTimer.cancel();
    }

    return oProvider;
}

From source file:org.brandroid.openmanager.fragments.DialogHandler.java

/**
 * Show a warning that has a specific count down to auto-cancel.
 * @param context Context.//from w  ww.  java 2 s.co m
 * @param msg Message String ID.
 * @param countSecs Length in seconds to show message before auto-cancelling.
 * @param onOK Callback for when "OK" is selected.
 * @return
 */
public static AlertDialog showWarning(final Context context, int msg, int countSecs,
        DialogInterface.OnClickListener onOK) {
    final Timer timer = new Timer("Count Down");
    final AlertDialog dlg = new AlertDialog.Builder(context).setMessage(msg)
            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    timer.cancel();
                }
            }).setCancelable(true).setPositiveButton(android.R.string.ok, onOK).show();
    final int[] cnt = new int[] { countSecs };
    final Button btCancel = dlg.getButton(DialogInterface.BUTTON_NEGATIVE);
    TimerTask tt = new TimerTask() {
        @Override
        public void run() {
            if (dlg.isShowing()) {
                btCancel.post(new Runnable() {
                    public void run() {
                        btCancel.setText(context.getResources().getString(android.R.string.cancel) + " ("
                                + cnt[0]-- + ")");
                    }
                });
            } else
                cnt[0] = 0;
            if (cnt[0] <= 0)
                cancel();
        }

        @Override
        public boolean cancel() {
            dlg.cancel();
            return super.cancel();
        }
    };
    timer.scheduleAtFixedRate(tt, 0, 1000);
    return dlg;
}

From source file:edu.missouri.bas.service.SensorService.java

public static void CancelTimers(Timer t) {
    //if(t1!=null&&t2!=null&&t3!=null&&t4!=null&&t5!=null&&t6!=null&&mTimer!=null)
    if (t != null) {
        t.cancel();
        t.purge();/*from w  ww .  j a  v  a2  s . c  o  m*/
        //mTimer.cancel();
    }
}

From source file:pt.lsts.neptus.plugins.controllers.ControllerManager.java

public void stop() {

    if (debug)//from w w w .  j  av a  2  s . co  m
        System.out.println("Stopping all controller manager timers");
    for (String v : activeControllers.keySet())
        activeControllers.get(v).stopControlling(VehiclesHolder.getVehicleById(v));

    activeControllers.clear();

    for (Timer t : timers.values()) {
        t.cancel();
        t.purge();
    }

    timers.clear();
}