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.gdgsp.fragment.PeopleFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_random:
        // Se o tamanho da lista for maior que 0 significa que j carregou
        if (selectedList.size() > 0) {
            // Aqui vai gerar um nmero aleatrio entre 0 e o tamanho da lista - 1
            Random random = new Random();
            int number = random.nextInt(selectedList.size());
            // Aps isso o aplicativo vai dar scroll e exibir a pessoa na posio do nmero aleatrio
            ((LinearLayoutManager) list.getLayoutManager()).scrollToPositionWithOffset(number, 0);

            if (person != null && selectedList.get(number).getId() == person.getId()) {
                count = 0;/*from w ww.  j ava  2s . c  o  m*/

                // Verifica o tanto de tempo que a pessoa ficou com o alerta aberto, se demorar muito vai ter coisa errada, como mudar a hora do sistema e aguardar o sorteio
                final Timer timer = new Timer();
                timer.scheduleAtFixedRate(new TimerTask() {
                    @Override
                    public void run() {
                        count++;
                    }
                }, 1000, 1000);

                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
                String localDate = sdf.format(new Date());
                SimpleDateFormat dbDateSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                final String dbDate = dbDateSDF.format(new Date());

                AlertDialog alertDialog = new AlertDialog.Builder(activity)
                        .setTitle(getString(R.string.raffle_person))
                        .setMessage("Voc!\n\nSorteado s " + localDate)
                        .setPositiveButton(getString(R.string.send), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface p1, int p2) {
                                timer.cancel();

                                sendRaffle(dbDate);
                            }
                        }).setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface p1, int p2) {
                                timer.cancel();
                            }
                        })

                        .create();

                alertDialog.setCanceledOnTouchOutside(false);
                alertDialog.show();
            } else {
                AlertDialog alertDialog = new AlertDialog.Builder(activity)
                        .setTitle(getString(R.string.raffle_person))
                        .setMessage(selectedList.get(number).getName()).setPositiveButton("OK", null).create();

                alertDialog.setCanceledOnTouchOutside(false);
                alertDialog.show();
            }
        }
        return true;
    case R.id.menu_hasapp:
        // Exibir apenas pessoas que usam o aplicativo, essa informao vem de um banco de dados no back-end
        item.setChecked(!item.isChecked());

        selectedList.clear();

        selectedList.addAll(item.isChecked() ? hasAppPeople : listPeople);

        adapter.notifyDataSetChanged();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:org.broad.igv.batch.CommandExecutorTest.java

@Test
public void testSortByRegionScoreType() throws Exception {
    Timer deadlockChecker = TestUtils.startDeadlockChecker(1000);
    String sessionPath = TestUtils.DATA_DIR + "sessions/metabric_expression.xml";
    TestUtils.loadSession(igv, sessionPath);

    Collection<RegionOfInterest> rois = igv.getSession().getAllRegionsOfInterest();

    List<Track> tracks;
    int count = 0;
    for (RegionOfInterest roi : rois) {
        for (RegionScoreType type : RegionScoreType.values()) {
            igv.sortAllTracksByAttributes(new String[] { "NAME" }, new boolean[] { false });
            String typeStr = type.toString().toUpperCase();
            if (count % 2 == 0) {
                typeStr = typeStr.toLowerCase();
            }//  w ww .java 2s . c  o m
            String resp = exec.execute("sort " + typeStr + " " + roi.getLocusString());
            assertEquals("OK", resp);

            tracks = igv.getAllTracks();
            ReferenceFrame frame = FrameManager.getDefaultFrame();
            IGVTestHeadless.checkIsSorted(tracks, roi, type, frame.getZoom(), frame);
            count++;
        }
    }
    deadlockChecker.cancel();
    deadlockChecker.purge();
}

From source file:com.csipsimple.service.DownloadLibService.java

private void dumpFile(HttpEntity entity, File partialDestinationFile, File destinationFile) throws IOException {
    if (!cancellingDownload) {
        totalSize = (int) entity.getContentLength();
        if (totalSize <= 0) {
            totalSize = 1024;/*from   w  w w  . j  av a  2  s. c  om*/
        }

        byte[] buff = new byte[64 * 1024];
        int read = 0;
        RandomAccessFile out = new RandomAccessFile(partialDestinationFile, "rw");
        out.seek(0);
        InputStream is = entity.getContent();
        TimerTask progressUpdateTimerTask = new TimerTask() {
            @Override
            public void run() {
                onProgressUpdate();
            }
        };
        Timer progressUpdateTimer = new Timer();
        try {
            // If File exists, set the Progress to it. Otherwise it will be
            // initial 0
            downloadedSize = 0;
            progressUpdateTimer.scheduleAtFixedRate(progressUpdateTimerTask, 100, 100);
            while ((read = is.read(buff)) > 0 && !cancellingDownload) {
                out.write(buff, 0, read);
                downloadedSize += read;
            }
            out.close();
            is.close();
            if (!cancellingDownload) {
                partialDestinationFile.renameTo(destinationFile);
            }
        } catch (IOException e) {
            out.close();
            try {
                destinationFile.delete();
            } catch (SecurityException ex) {
                Log.e(THIS_FILE, "Unable to delete downloaded File. Continue anyway.", ex);
            }
        } finally {
            progressUpdateTimer.cancel();
            buff = null;
        }
    }
}

From source file:com.github.abilityapi.abilityapi.external.Metrics.java

private void startSubmitting() {
    // We use a timer cause want to be independent from the server tps
    final Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override/* ww  w.j  ava 2 s. c o m*/
        public void run() {
            // Plugin was disabled, e.g. because of a reload (is this even possible in Sponge?)
            if (!Sponge.getPluginManager().isLoaded(plugin.getId())) {
                timer.cancel();
                return;
            }
            // The data collection (e.g. for custom graphs) is done sync
            // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
            Scheduler scheduler = Sponge.getScheduler();
            Task.Builder taskBuilder = scheduler.createTaskBuilder();
            taskBuilder.execute(() -> submitData()).submit(plugin);
        }
    }, 1000 * 60 * 5, 1000 * 60 * 30);
    // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
    // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
    // WARNING: Just don't do it!
}

From source file:com.jredrain.startup.AgentProcessor.java

@Override
public Response execute(final Request request) throws TException {
    if (!this.password.equalsIgnoreCase(request.getPassword())) {
        return errorPasswordResponse(request);
    }/*  ww  w.jav  a 2s  .co  m*/

    String command = request.getParams().get("command") + EXITCODE_SCRIPT;

    String pid = request.getParams().get("pid");
    //??
    Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L);

    boolean timeoutFlag = timeout > 0;

    logger.info("[redrain]:execute:{},pid:{}", command, pid);

    File shellFile = CommandUtils.createShellFile(command, pid);

    Integer exitValue;

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    final Response response = Response.response(request);

    final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE);

    final Timer timer = new Timer();

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try {
        CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath());
        final DefaultExecutor executor = new DefaultExecutor();

        ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream);
        executor.setStreamHandler(stream);
        response.setStartTime(new Date().getTime());
        //?0,shell
        executor.setExitValue(0);

        if (timeoutFlag) {
            //...
            executor.setWatchdog(watchdog);
            //
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //,kill...
                    if (watchdog.isWatching()) {
                        /**
                         * watchdogdestroyProcesskill...
                         * watchdog.destroyProcess();
                         */
                        timer.cancel();
                        watchdog.stop();
                        //call  kill...
                        request.setAction(Action.KILL);
                        try {
                            kill(request);
                            response.setExitCode(RedRain.StatusCode.TIME_OUT.getValue());
                        } catch (TException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }, timeout * 60 * 1000);

            //
            resultHandler = new DefaultExecuteResultHandler() {
                @Override
                public void onProcessComplete(int exitValue) {
                    super.onProcessComplete(exitValue);
                    timer.cancel();
                }

                @Override
                public void onProcessFailed(ExecuteException e) {
                    super.onProcessFailed(e);
                    timer.cancel();
                }
            };
        }

        executor.execute(commandLine, resultHandler);

        resultHandler.waitFor();

    } catch (Exception e) {
        if (e instanceof ExecuteException) {
            exitValue = ((ExecuteException) e).getExitValue();
        } else {
            exitValue = RedRain.StatusCode.ERROR_EXEC.getValue();
        }
        if (RedRain.StatusCode.KILL.getValue().equals(exitValue)) {
            if (timeoutFlag) {
                timer.cancel();
                watchdog.stop();
            }
            logger.info("[redrain]:job has be killed!at pid :{}", request.getParams().get("pid"));
        } else {
            logger.info("[redrain]:job execute error:{}", e.getCause().getMessage());
        }
    } finally {

        exitValue = resultHandler.getExitValue();

        if (CommonUtils.notEmpty(outputStream.toByteArray())) {
            try {
                outputStream.flush();
                String text = outputStream.toString();
                if (notEmpty(text)) {
                    try {
                        text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), "");
                        response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY)));
                        exitValue = Integer.parseInt(text
                                .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim());
                    } catch (IndexOutOfBoundsException e) {
                        response.setMessage(text);
                    }
                }
                outputStream.close();
            } catch (Exception e) {
                logger.error("[redrain]:error:{}", e);
            }
        }

        if (RedRain.StatusCode.TIME_OUT.getValue() == response.getExitCode()) {
            response.setSuccess(false).end();
        } else {
            response.setExitCode(exitValue)
                    .setSuccess(response.getExitCode() == RedRain.StatusCode.SUCCESS_EXIT.getValue()).end();
        }

        if (shellFile != null) {
            shellFile.delete();//
        }
    }
    logger.info("[redrain]:execute result:{}", response.toString());
    watchdog.stop();

    return response;
}

From source file:coffeshop.PaymentPage.java

private void btcTimer() {
    Timer timer = new Timer(); //new timer
    timeExpired = false;// w  w w.  j  ava 2  s . c  om
    TimerTask task = new TimerTask() {
        int counter = 10;

        public void run() {
            int minutes = 0;
            int seconds = 0;
            minutes = counter / 60;
            seconds = counter % 60;
            if (timeStop) {
                timer.cancel();
                timer.purge();
            } else {
                String timeString = String.format("Time Left: %02d:%02d", minutes, seconds);
                lblTimer.setText(timeString);
                counter--;
                if (counter == -1) {
                    timer.cancel();
                    timer.purge();
                    lblTimer.setText("Time Expired");
                    timeExpired = true;
                    lblQRC.setIcon(defaultQR);
                }
            }

        }
    };
    timer.scheduleAtFixedRate(task, 1000, 1000);
}

From source file:org.opencron.agent.AgentProcessor.java

@Override
public Response execute(final Request request) throws TException {
    if (!this.password.equalsIgnoreCase(request.getPassword())) {
        return errorPasswordResponse(request);
    }//from  w w w.  j ava2 s  . com

    String command = request.getParams().get("command") + EXITCODE_SCRIPT;

    String pid = request.getParams().get("pid");
    //??
    Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L);

    boolean timeoutFlag = timeout > 0;

    logger.info("[opencron]:execute:{},pid:{}", command, pid);

    File shellFile = CommandUtils.createShellFile(command, pid);

    Integer exitValue;

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    final Response response = Response.response(request);

    final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE);

    final Timer timer = new Timer();

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try {
        CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath());
        final DefaultExecutor executor = new DefaultExecutor();

        ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream);
        executor.setStreamHandler(stream);
        response.setStartTime(new Date().getTime());
        //?0,shell
        executor.setExitValue(0);

        if (timeoutFlag) {
            //...
            executor.setWatchdog(watchdog);
            //
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //,kill...
                    if (watchdog.isWatching()) {
                        /**
                         * watchdogdestroyProcesskill...
                         * watchdog.destroyProcess();
                         */
                        timer.cancel();
                        watchdog.stop();
                        //call  kill...
                        request.setAction(Action.KILL);
                        try {
                            kill(request);
                            response.setExitCode(Opencron.StatusCode.TIME_OUT.getValue());
                        } catch (TException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }, timeout * 60 * 1000);

            //
            resultHandler = new DefaultExecuteResultHandler() {
                @Override
                public void onProcessComplete(int exitValue) {
                    super.onProcessComplete(exitValue);
                    timer.cancel();
                }

                @Override
                public void onProcessFailed(ExecuteException e) {
                    super.onProcessFailed(e);
                    timer.cancel();
                }
            };
        }

        executor.execute(commandLine, resultHandler);

        resultHandler.waitFor();

    } catch (Exception e) {
        if (e instanceof ExecuteException) {
            exitValue = ((ExecuteException) e).getExitValue();
        } else {
            exitValue = Opencron.StatusCode.ERROR_EXEC.getValue();
        }
        if (Opencron.StatusCode.KILL.getValue().equals(exitValue)) {
            if (timeoutFlag) {
                timer.cancel();
                watchdog.stop();
            }
            logger.info("[opencron]:job has be killed!at pid :{}", request.getParams().get("pid"));
        } else {
            logger.info("[opencron]:job execute error:{}", e.getCause().getMessage());
        }
    } finally {

        exitValue = resultHandler.getExitValue();

        if (CommonUtils.notEmpty(outputStream.toByteArray())) {
            try {
                outputStream.flush();
                String text = outputStream.toString();
                if (notEmpty(text)) {
                    try {
                        text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), "");
                        response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY)));
                        exitValue = Integer.parseInt(text
                                .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim());
                    } catch (IndexOutOfBoundsException e) {
                        response.setMessage(text);
                    }
                }
                outputStream.close();
            } catch (Exception e) {
                logger.error("[opencron]:error:{}", e);
            }
        }

        if (Opencron.StatusCode.TIME_OUT.getValue() == response.getExitCode()) {
            response.setSuccess(false).end();
        } else {
            response.setExitCode(exitValue)
                    .setSuccess(response.getExitCode() == Opencron.StatusCode.SUCCESS_EXIT.getValue()).end();
        }

        if (shellFile != null) {
            shellFile.delete();//
        }
    }
    logger.info("[opencron]:execute result:{}", response.toString());
    watchdog.stop();

    return response;
}

From source file:me.rojo8399.placeholderapi.impl.Metrics.java

private void startSubmitting() {
    // We use a timer cause want to be independent from the server tps
    final Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override//ww  w  .j a  v  a 2s  .c om
        public void run() {
            // Plugin was disabled, e.g. because of a reload (is this even
            // possible in Sponge?)
            if (!Sponge.getPluginManager().isLoaded(plugin.getId())) {
                timer.cancel();
                return;
            }
            // The data collection (e.g. for custom graphs) is done sync
            // Don't be afraid! The connection to the bStats server is still
            // async, only the stats collection is sync ;)
            Scheduler scheduler = Sponge.getScheduler();
            Task.Builder taskBuilder = scheduler.createTaskBuilder();
            taskBuilder.execute(() -> submitData()).submit(plugin);
        }
    }, 1000 * 60 * 5, 1000 * 60 * 30);
    // Submit the data every 30 minutes, first time after 5 minutes to give
    // other plugins enough time to start
    // WARNING: Changing the frequency has no effect but your plugin WILL be
    // blocked/deleted!
    // WARNING: Just don't do it!
}

From source file:org.openhab.binding.maxcul.internal.MaxCulBinding.java

/**
 * @{inheritDoc/*  w  w w  . j av  a 2s  .  co m*/
 */
@Override
protected void internalReceiveCommand(final String itemName, Command command) {
    Timer pairModeTimer = null;

    MaxCulBindingConfig bindingConfig = null;
    for (MaxCulBindingProvider provider : super.providers) {
        bindingConfig = provider.getConfigForItemName(itemName);
        if (bindingConfig != null) {
            break;
        }
    }
    logger.debug("Received command " + command.toString() + " for item " + itemName);
    if (bindingConfig != null) {
        logger.debug("Found config for " + itemName);

        switch (bindingConfig.getDeviceType()) {
        case PAIR_MODE:
            if ((command instanceof OnOffType)) {
                switch ((OnOffType) command) {
                case ON:
                    /*
                     * turn on pair mode and schedule disabling of pairing
                     * mode
                     */
                    pairMode = true;
                    TimerTask task = new TimerTask() {
                        public void run() {
                            logger.debug(itemName + " pairMode time out executed");
                            pairMode = false;
                            eventPublisher.postUpdate(itemName, OnOffType.OFF);
                        }
                    };
                    pairModeTimer = timers.get(itemName);
                    if (pairModeTimer != null) {
                        pairModeTimer.cancel();
                        timers.remove(itemName);
                    }
                    pairModeTimer = new Timer();
                    timers.put(itemName, pairModeTimer);
                    pairModeTimer.schedule(task, pairModeTimeout);
                    logger.debug(itemName + " pairMode enabled & timeout scheduled");
                    break;
                case OFF:
                    /*
                     * we are manually disabling, so clear the timer and the
                     * flag
                     */
                    pairMode = false;
                    pairModeTimer = timers.get(itemName);
                    if (pairModeTimer != null) {
                        logger.debug(itemName + " pairMode timer cancelled");
                        pairModeTimer.cancel();
                        timers.remove(itemName);
                    }
                    logger.debug(itemName + " pairMode cleared");
                    break;
                }
            } else
                logger.warn(
                        "Command not handled for " + bindingConfig.getDeviceType() + " that is not OnOffType");
            break;
        case LISTEN_MODE:
            if (command instanceof OnOffType) {
                this.messageHandler.setListenMode(((OnOffType) command == OnOffType.ON));
            } else
                logger.warn(
                        "Command not handled for " + bindingConfig.getDeviceType() + " that is not OnOffType");
            break;
        case RADIATOR_THERMOSTAT:
        case RADIATOR_THERMOSTAT_PLUS:
        case WALL_THERMOSTAT:
            if (bindingConfig.getFeature() == MaxCulFeature.THERMOSTAT) {
                /* clear out old pacing timer */
                if (pacedBindingTransmitTimers.containsKey(bindingConfig)) {
                    pacedBindingTransmitTimers.get(bindingConfig).cancel();
                    pacedBindingTransmitTimers.remove(bindingConfig);
                }
                /* schedule new timer */
                Timer pacingTimer = new Timer();
                pacedBindingTransmitTimers.put(bindingConfig, pacingTimer);
                pacingTimer.schedule(new MaxCulPacedThermostatTransmitTask(command, bindingConfig,
                        messageHandler, super.providers), PACED_TRANSMIT_TIME);
            } else if (bindingConfig.getFeature() == MaxCulFeature.RESET) {
                messageHandler.sendReset(bindingConfig.getDevAddr());
            } else {
                logger.warn("Command not handled for " + bindingConfig.getDeviceType()
                        + " that is not OnOffType or DecimalType");
            }
            break;
        default:
            logger.warn("Command not handled for " + bindingConfig.getDeviceType());
            break;
        }
    }
    updateCreditMonitors();
}

From source file:org.getobjects.eoaccess.EOAdaptor.java

public void dispose() {
    /* Note: we also dispose channels which are checked out! */
    List<EOAdaptorChannel> channels1 = null, channels2 = null;
    Timer timer = null;

    synchronized (this) {
        channels1 = this.availableChannels;
        channels2 = this.checkedOutChannels;
        timer = this.maintenanceTimer;
        this.availableChannels = null;
        this.checkedOutChannels = null;
        this.maintenanceTimer = null;
    }/*from  ww  w  .  j  a  va 2 s  . c o  m*/

    if (channels1 != null) {
        for (EOAdaptorChannel channel : channels1)
            channel.dispose();
    }
    if (channels2 != null) {
        for (EOAdaptorChannel channel : channels2)
            channel.dispose();
    }

    if (timer != null) {
        timer.cancel();
        timer = null;
    }
}