Example usage for java.util TimerTask TimerTask

List of usage examples for java.util TimerTask TimerTask

Introduction

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

Prototype

protected TimerTask() 

Source Link

Document

Creates a new timer task.

Usage

From source file:at.pardus.android.browser.PardusMessageChecker.java

/**
 * Resumes the background message checking.
 *///from w  w w .j  av a  2 s .  c o m
public void resume() {
    if (PardusConstants.DEBUG) {
        Log.v(this.getClass().getSimpleName(), "Resuming Pardus Message Checker");
    }
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLIS);
    HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLIS);
    HttpConnectionParams.setSocketBufferSize(httpParams, 4096);
    HttpProtocolParams.setVersion(httpParams, new ProtocolVersion("HTTP", 1, 0));
    httpClient = new DefaultHttpClient(httpParams);
    task = new TimerTask() {

        @Override
        public void run() {
            check();
        }

    };
    timer.schedule(task, 1500, delayMillis);
}

From source file:deincraftlauncher.InstallController.java

@FXML
void Continue() {

    if (!loggedin) {
        popupMessage("Fehler: Bitte zuerst erst anmelden");

    } else {//from  w ww. j  av a  2 s  .c o  m

        System.out.println("Creating config file...");
        try {
            folder.mkdirs();
            config.createNewFile();
        } catch (IOException ex) {
            System.err.println("error creating config file: " + ex);
        }

        settings.setPassword(Password);
        settings.setUsername(Username);
        settings.setRAM(getDefaultRam());
        settings.save();

        /*folderLauncher = new File(targetPath + "Launcher");
        System.out.println("Launcher: " + folderLauncher);
        folderLauncher.mkdirs();
        folderGame = new File(targetPath + "Games");
        folderGame.mkdirs();*/
        createGameDir(targetPath);
        if (createDesktop.isSelected()) {
            createDesktopShortcut();
        }

        popupMessage("Installation abgeschlossen. Starte Minefactory Launcher...");
        mainPanel.setVisible(false);
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            Logger.getLogger(InstallController.class.getName()).log(Level.SEVERE, null, ex);
        }
        File installlocation = new File(targetPath);
        installlocation.mkdirs();
        saveConfig();
        String jarFile = getDCFile();
        String command = "java -jar " + jarFile;
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.exit(0);
            }
        }, 4000);
        try {
            Process p = Runtime.getRuntime().exec("cmd /C " + command);
            BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            try {
                while ((line = stdout.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                System.err.println(e);
            }
        } catch (IOException ex) {
            Logger.getLogger(InstallController.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    System.out.println("Finishing setting dialog...");
}

From source file:hydrograph.server.execution.tracking.client.main.HydrographMain.java

/**
 *    /*from ww w. j  a v  a 2 s.  c  o m*/
 * @param latch
 * @param session
 * @param jobId
 * @param timer
 * @param execution
 * @param socket
 * @throws IOException
 */
private void sendExecutionTrackingStatus(final CountDownLatch latch, Session session, final String jobId,
        final Timer timer, final HydrographService execution, final HydrographEngineCommunicatorSocket socket)
        throws IOException {
    try {
        TimerTask task = new TimerTask() {
            ExecutionStatus previousExecutionStatus = null;

            @Override
            public void run() {
                List<ComponentInfo> componentInfos = execution.getStatus();
                if (!componentInfos.isEmpty()) {
                    List<ComponentStatus> componentStatusList = new ArrayList<ComponentStatus>();
                    for (ComponentInfo componentInfo : componentInfos) {
                        ComponentStatus componentStatus = new ComponentStatus(componentInfo.getComponentId(),
                                componentInfo.getComponentName(), componentInfo.getCurrentStatus(),
                                componentInfo.getBatch(), componentInfo.getProcessedRecords());
                        componentStatusList.add(componentStatus);
                    }
                    ExecutionStatus executionStatus = new ExecutionStatus(componentStatusList);
                    executionStatus.setJobId(jobId);
                    executionStatus.setClientId(Constants.ENGINE_CLIENT + jobId);
                    executionStatus.setType(Constants.POST);
                    Gson gson = new Gson();
                    try {
                        if (previousExecutionStatus == null
                                || !executionStatus.equals(previousExecutionStatus)) {
                            socket.sendMessage(gson.toJson(executionStatus));
                            previousExecutionStatus = executionStatus;
                        }
                    } catch (IOException e) {
                        logger.error("Fail to send status for job - " + jobId, e);
                        timer.cancel();
                    }

                    if (StringUtils.isNotBlank(jobId)) {
                        //moved this after sendMessage in order to log even if the service is not running 
                        ExecutionTrackingFileLogger.INSTANCE.log(jobId, executionStatus);
                    }

                }
                if (!execution.getJobRunningStatus()) {
                    timer.cancel();
                    latch.countDown();
                }
            }
        };

        timer.schedule(task, 0l, ExecutionTrackingUtils.INSTANCE.getStatusFrequency());
        latch.await();

    } catch (Throwable t) {
        logger.error("Failure in job - " + jobId, t);
        timer.cancel();
        throw new RuntimeException(t);
    } finally {

        if (session != null && session.isOpen()) {
            logger.debug("Closing Websocket engine client");
            CloseReason closeReason = new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Session Closed");
            session.close(closeReason);
        }
    }
}

From source file:org.griphyn.vdl.karajan.monitor.monitors.swing.GraphPanel.java

private synchronized void scheduleTooltipDisplay(final double x) {
    if (tooltipTimerTask != null) {
        tooltipTimerTask.cancel();/*from  w  w w . ja  va 2 s  .c o  m*/
    }
    tooltipTimerTask = new TimerTask() {
        @Override
        public void run() {
            tooltipTimerTask = null;
            enableTooltip(x);
        }
    };
    try {
        GlobalTimer.getTimer().schedule(tooltipTimerTask, TOOLTIP_DISPLAY_DELAY);
    } catch (IllegalStateException e) {
        System.err.println(this + ": " + e.getMessage());
    }
}

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

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

        @Override//w w  w. j  av  a  2s. c om
        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:edu.wisc.nexus.auth.gidm.config.AbstractRefreshingFileLoader.java

private final void loadConfiguration(C configuration) {
    this.configReadWriteLock.writeLock().lock();
    try {/*  www  . j  av  a2  s . com*/
        //Cancel the refresh timer if it exists
        if (configurationRefresh != null) {
            configurationRefresh.cancel();
            configurationRefresh = null;
            this.configurationSaveTimer.purge();
        }

        this.postLoad(configuration);

        final int refreshInterval = getRefreshInterval(configuration);
        if (refreshInterval > 0) {
            //Create a new task to periodically save the user cache
            this.configurationRefresh = new TimerTask() {
                @Override
                public void run() {
                    refreshConfiguration();
                }
            };

            final long period = TimeUnit.SECONDS.toMillis(refreshInterval);
            this.configurationSaveTimer.schedule(this.configurationRefresh, period, period);
        }
    } finally {
        this.configReadWriteLock.writeLock().unlock();
    }
}

From source file:cz.dasnet.dasik.Dasik.java

@Override
protected void onConnect() {
    log.info("Connected on " + getServer());
    auth();/*w  ww . jav  a  2 s.  c o  m*/
    if (authed) {
        requestInvites();
    }
    final Dasik bot = this;
    try {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                bot.joinChannels();
            }
        }, 1000);

        TimerTask dumpTask = new TimerTask() {

            @Override
            public void run() {
                Document document = DocumentHelper.createDocument();
                Element channelinfo = document.addElement("channelinfo");

                for (String c : activeChannels.keySet()) {
                    Element channel = channelinfo.addElement("channel");
                    Element name = channel.addElement("name");
                    name.setText(c);
                    Element size = channel.addElement("size");
                    size.setText("" + getUsers(c).length);
                }

                Element updatetime = channelinfo.addElement("updatetime");
                updatetime.setText(new Long(new Date().getTime() / 1000).toString());

                try {
                    XMLWriter writer = new XMLWriter(new FileWriter("channelinfo.xml"));
                    writer.write(document);
                    writer.close();
                } catch (IOException ex) {
                    log.error("Unable to dump channel info", ex);
                }
            }
        };

        Timer dump = new Timer("dump", true);
        dump.schedule(dumpTask, 10000, 60000);
    } catch (Exception ex) {
        this.joinChannels();
        log.error("Channel autojoin timer failed to schedule the task.", ex);
    }
}

From source file:io.hawkcd.agent.Agent.java

private void startReportAgentTimer() {

    TimerTask reportAgentTask = new TimerTask() {
        @Override//  ww w  .  j  a va  2 s  .c  o  m
        public void run() {
            Agent.this.reportAgentToServer();
        }
    };
    this.reportAgentTimer = new Timer();
    this.reportAgentTimer.schedule(reportAgentTask, 0, 4000);
}

From source file:com.example.ecgfile.DeviceControlActivity.java

public void TimerTask() {
    if (mTimer == null) {
        mTimer = new Timer();
    }//from  ww w  . ja v a2 s. com
    mTimerTask = new TimerTask() {
        @Override
        public void run() {
            if (!mButton_remoteUpload_enable.isChecked()) {
                cleanTimerTask();
            }
            SimpleDateFormat formatter = new SimpleDateFormat("/yyyy-MM-dd HH:mm:ss");
            Date curDate = new Date(System.currentTimeMillis());
            timeString = formatter.format(curDate);
        }
    };
    mTimer.schedule(mTimerTask, 0, CommonVar.PERIOD_15);
}

From source file:com.enjoyxstudy.selenium.autoexec.AutoExecServer.java

/**
 * server startup.//from   w w  w . java  2s  .  c  om
 *
 * @param properties
 * @throws Exception
 */
public void startup(Properties properties) throws Exception {

    configuration = new AutoExecServerConfiguration(properties);

    if (configuration.getProxyHost() != null) {
        System.setProperty("http.proxyHost", configuration.getProxyHost());
    }
    if (configuration.getProxyPort() != null) {
        System.setProperty("http.proxyPort", configuration.getProxyPort());
    }

    seleniumServer = new SeleniumServer(configuration);

    if (configuration.getUserExtensions() != null) {
        seleniumServer.addNewStaticContent(configuration.getUserExtensions().getParentFile());
    }

    mailConfiguration = new MailConfiguration(properties);

    Server server = seleniumServer.getServer();

    // add context
    HttpContext rootContext = new HttpContext();
    rootContext.setContextPath(CONTEXT_PATH_ROOT);
    rootContext.setResourceBase(CONTENTS_DIR);
    rootContext.addHandler(new ResourceHandler());
    server.addContext(rootContext);

    HttpContext commandContext = new HttpContext();
    commandContext.setContextPath(CONTEXT_PATH_COMMAND);
    commandContext.addHandler(new CommandHandler(this));
    server.addContext(commandContext);

    HttpContext resultContext = new HttpContext();
    resultContext.setContextPath(CONTEXT_PATH_RESULT);
    resultContext.setResourceBase(configuration.getResultDir().getAbsolutePath());
    resultContext.addHandler(new ResourceHandler());
    server.addContext(resultContext);

    seleniumServer.start();

    if (configuration.getAutoExecTime() != null) {
        // set auto exec timer

        String[] time = configuration.getAutoExecTime().split(":");

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
        calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        log.info("Auto exec first time: " + calendar.getTime());

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                try {
                    log.info("Start auto exec.");
                    process();
                    log.info("End auto exec.");
                } catch (Exception e) {
                    log.error("Error auto exec.");
                }
            }
        }, calendar.getTime(), 1000 * 60 * 60 * 24);
    }

    log.info("Start Selenium Auto Exec Server.");
}