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:com.github.safrain.remotegsh.server.RgshFilter.java

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    if (filterConfig.getInitParameter("charset") != null) {
        charset = filterConfig.getInitParameter("charset");
    } else {/* w  w w.j av  a 2s . c om*/
        charset = DEFAULT_CHARSET;
    }

    if (filterConfig.getInitParameter("shellSessionTimeout") != null) {
        shellSessionTimeout = Long.valueOf(filterConfig.getInitParameter("shellSessionTimeout"));
    } else {
        shellSessionTimeout = SESSION_PURGE_INTERVAL;
    }

    String scriptExtensionCharset;
    if (filterConfig.getInitParameter("scriptExtensionCharset") != null) {
        scriptExtensionCharset = filterConfig.getInitParameter("scriptExtensionCharset");
    } else {
        scriptExtensionCharset = DEFAULT_CHARSET;
    }

    //Compile script extensions
    List<String> scriptExtensionPaths = new ArrayList<String>();
    if (filterConfig.getInitParameter("scriptExtensions") != null) {
        Collections.addAll(scriptExtensionPaths, filterConfig.getInitParameter("scriptExtensions").split(","));
    } else {
        scriptExtensionPaths.add(RESOURCE_PATH + "extension/spring.groovy");
    }

    scriptExtensions = new HashMap<String, CompiledScript>();
    for (String path : scriptExtensionPaths) {
        String scriptContent;
        try {
            scriptContent = getResource(path, scriptExtensionCharset);
        } catch (IOException e) {
            throw new ServletException(e);
        }

        Compilable compilable = (Compilable) createGroovyEngine();
        try {
            CompiledScript compiledScript = compilable.compile(scriptContent);
            scriptExtensions.put(path, compiledScript);
        } catch (ScriptException e) {
            //Ignore exceptions while compiling script extensions,there may be compilation errors due to missing dependency
            log.log(Level.WARNING, String.format("Error compiling script extension '%s'", path), e);
        }
    }

    // Setup a timer to purge timeout shell sessions
    Timer timer = new Timer("Remote Groovy Shell session purge daemon", true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            purgeTimeOutSessions();
        }
    }, 0, SESSION_PURGE_INTERVAL);
}

From source file:com.adaptris.core.jms.activemq.ActiveMqJmsTransactedWorkflowTest.java

public void testHandleChannelUnavailable_Bug2343() throws Exception {
    int msgCount = 10;
    EmbeddedActiveMq activeMqBroker = new EmbeddedActiveMq();
    String destination = createSafeUniqueId(new Object());
    final Channel channel = createStartableChannel(activeMqBroker, true, "testHandleChannelUnavailable_Bug2343",
            destination);/*  w ww .j a v a  2  s.  c  om*/
    JmsTransactedWorkflow workflow = (JmsTransactedWorkflow) channel.getWorkflowList().get(0);
    workflow.setChannelUnavailableWaitInterval(new TimeInterval(1L, TimeUnit.SECONDS));
    try {
        activeMqBroker.start();
        channel.requestStart();
        channel.toggleAvailability(false);
        Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                channel.toggleAvailability(true);
            }

        }, 666);
        StandaloneProducer sender = new StandaloneProducer(activeMqBroker.getJmsConnection(),
                new PtpProducer(new ConfiguredProduceDestination(destination)));
        send(sender, msgCount);
        waitForMessages((MockMessageProducer) workflow.getProducer(), msgCount);
        assertEquals(msgCount, ((MockMessageProducer) workflow.getProducer()).getMessages().size());
    } finally {
        channel.requestClose();
    }
    assertEquals(0, activeMqBroker.messagesOnQueue(destination));
    activeMqBroker.destroy();
}

From source file:edu.wisc.jmeter.dao.JdbcMonitorDao.java

@Override
public void afterPropertiesSet() throws Exception {
    this.setupTables();

    this.purgingTimer = new Timer("JdbcMonitorDao_PurgingTimer", true);
    this.purgingTimer.schedule(new TimerTask() {
        @Override/* w  w w  . j  a  v a 2s.  c o m*/
        public void run() {
            purgeFailureLog(new Date(System.currentTimeMillis() - purgeOldFailure));
            purgeRequestLog(new Date(System.currentTimeMillis() - purgeOldStatus));
            purgeStatusCache(new Date(System.currentTimeMillis() - purgeStatusCache)); //HostStatus objects can be rebuilt, don't hold stuff older than 5 minutes
        }
    }, 1000 * 60, //Run 1 minute after starting 
            1000 * 60 * 5); //Repeat every 5 minutes
}

From source file:org.nuvola.tvshowtime.ApplicationLauncher.java

private void requestAccessToken() {
    try {/*from   w  ww. j a va2  s. co m*/
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<String> entity = new HttpEntity<>("client_id=" + TVST_CLIENT_ID, headers);

        ResponseEntity<AuthorizationCode> content = tvShowTimeTemplate.exchange(TVST_AUTHORIZE_URI, POST,
                entity, AuthorizationCode.class);
        AuthorizationCode authorizationCode = content.getBody();

        if (authorizationCode.getResult().equals("OK")) {
            LOG.info("Linking with your TVShowTime account using the code "
                    + authorizationCode.getDevice_code());
            LOG.info("Please open the URL " + authorizationCode.getVerification_url() + " in your browser");
            LOG.info("Connect with your TVShowTime account and type in the following code : ");
            LOG.info(authorizationCode.getUser_code());
            LOG.info("Waiting for you to type in the code in TVShowTime :-D ...");

            tokenTimer = new Timer();
            tokenTimer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    loadAccessToken(authorizationCode.getDevice_code());
                }
            }, 1000 * authorizationCode.getInterval(), 1000 * authorizationCode.getInterval());
        } else {
            LOG.error("OAuth authentication TVShowTime failed.");

            System.exit(1);
        }
    } catch (Exception e) {
        LOG.error("OAuth authentication TVShowTime failed.");
        LOG.error(e.getMessage());

        System.exit(1);
    }
}

From source file:com.meltmedia.cadmium.core.messaging.jgroups.JGroupsMembershipTracker.java

private void handleSyncRequest(View new_view) {
    log.info("Here is the new view {}", new_view);
    final ChannelMember coordinator = getCoordinator();
    if (coordinator != null && !coordinator.isMine()) {
        timer.schedule(new TimerTask() {
            public void run() {
                log.debug("I'm not the coordinator!!!");
                if (gitService != null) {
                    try {
                        log.debug("Waiting for content git service to initialize.");
                        gitService.getGitService();
                        gitService.releaseGitService();
                    } catch (Throwable t) {
                    }//from w  w  w. ja va2 s .  co m
                }
                if (configGitService != null) {
                    try {
                        log.debug("Waiting for config git service to initialize.");
                        configGitService.getGitService();
                        configGitService.releaseGitService();
                    } catch (Throwable t) {
                    }
                }
                Properties configProperties = configManager.getDefaultProperties();
                SyncRequest request = new SyncRequest();
                if (configProperties.containsKey("repo") && configProperties.containsKey("branch")
                        && configProperties.containsKey("git.ref.sha")) {
                    request.setContentLocation(new GitLocation(configProperties.getProperty("repo"),
                            configProperties.getProperty("branch"),
                            configProperties.getProperty("git.ref.sha")));
                    log.info("I have repo:{}, branch:{}, and sha:{} for content",
                            new Object[] { configProperties.getProperty("repo"),
                                    configProperties.getProperty("branch"),
                                    configProperties.getProperty("git.ref.sha") });
                }
                if (configProperties.containsKey("config.repo") && configProperties.containsKey("config.branch")
                        && configProperties.containsKey("config.git.ref.sha")) {
                    request.setConfigLocation(new GitLocation(configProperties.getProperty("config.repo"),
                            configProperties.getProperty("config.branch"),
                            configProperties.getProperty("config.git.ref.sha")));
                    log.info("I have repo:{}, branch:{}, and sha:{} for configuration",
                            new Object[] { configProperties.getProperty("config.repo"),
                                    configProperties.getProperty("config.branch"),
                                    configProperties.getProperty("config.git.ref.sha") });
                }
                Message<SyncRequest> syncMessage = new Message<SyncRequest>(ProtocolMessage.SYNC, request);
                try {
                    sender.sendMessage(syncMessage, coordinator);
                } catch (Exception e) {
                    log.warn("Failed to send sync message: {}", e.getMessage());
                }
            }
        }, 50l);
    }
}

From source file:com.datatorrent.flume.source.HdfsTestSource.java

@Override
public void start() {
    super.start();
    emitTimer = new Timer();

    final ChannelProcessor channelProcessor = getChannelProcessor();
    emitTimer.scheduleAtFixedRate(new TimerTask() {
        @Override//from w w w  .  ja  v  a2 s .com
        public void run() {
            int lineCount = 0;
            events.clear();
            try {
                while (lineCount < rate && !finished) {
                    String line = br.readLine();

                    if (line == null) {
                        logger.debug("completed file {}", currentFile);
                        br.close();
                        currentFile++;
                        if (currentFile == dataFiles.size()) {
                            logger.info("finished all files");
                            finished = true;
                            break;
                        }
                        Path filePath = new Path(dataFiles.get(currentFile));
                        br = new BufferedReader(
                                new InputStreamReader(new GzipCompressorInputStream(fs.open(filePath))));
                        logger.info("opening file {}. {}", currentFile, filePath);
                        continue;
                    }
                    lineCount++;
                    Event flumeEvent = EventBuilder.withBody(line.getBytes());
                    events.add(flumeEvent);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (events.size() > 0) {
                channelProcessor.processEventBatch(events);
            }
            if (finished) {
                emitTimer.cancel();
            }
        }

    }, 0, 1000);
}

From source file:de.uni_koeln.spinfo.maalr.webapp.controller.EditorController.java

@Override
public String export(Set<String> fields, EditorQuery query) throws NoDatabaseAvailableException, IOException {
    File dir = new File("exports");
    dir.mkdirs();//  w ww . j av  a2 s .  c  o m
    final File tmp = new File(dir, "export_" + UUID.randomUUID() + ".tsv.zip");
    Timer timer = new Timer();
    service.export(fields, query, tmp);
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            if (tmp.exists()) {
                System.out.println("Deleting file " + tmp);
                tmp.delete();
            }
        }
    }, 60000 * 30);
    return tmp.getName();
}

From source file:Main.IrcBot.java

public void serverConnect() {
    try {/*from  w ww  .  j  a  va 2 s.  c  o  m*/
        Socket ircSocket = new Socket(this.hostName, this.portNumber);

        if (ircSocket.isConnected()) {
            final PrintWriter out = new PrintWriter(ircSocket.getOutputStream(), true);
            final BufferedReader in = new BufferedReader(new InputStreamReader(ircSocket.getInputStream()));
            final BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

            String userInput;
            String pass = "PASS *";
            String nick = "NICK " + this.name;
            String user = "USER " + this.name + " 8 * :" + this.name;
            String channel = "JOIN " + this.channel;
            Timer channelChecker = new Timer();

            out.println(pass);
            System.out.println("echo: " + in.readLine().toString());
            out.println(nick);
            System.out.println("echo: " + in.readLine().toString());
            out.println(user);
            System.out.println("echo: " + in.readLine().toString());
            out.println(channel);

            channelChecker.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    try {
                        String userIn = in.readLine().toString();
                        ;
                        System.out.println(userIn);

                        if (userIn.contains("PING")) {
                            out.println("PONG hobana.freenode.net");
                        }

                        if (userIn.contains("http://pastebin.com")) {
                            //String[] urlCode = userIn.split("[http://pastebin.com]");

                            String url = "http://pastebin.com";
                            int indexStart = userIn.indexOf(url);
                            int indexStop = userIn.indexOf(" ", indexStart);
                            String urlCode = userIn.substring(indexStart, indexStop);
                            String pasteBinId = urlCode.substring(urlCode.indexOf("/", 9) + 1,
                                    urlCode.length());
                            System.out.println(pasteBinId);

                            IrcBot.postRequest(pasteBinId, out);
                        }

                    } catch (Exception j) {

                    }
                }
            }, 100, 100);

        } else {
            System.out.println("There was an error connecting to the IRC server: " + this.hostName
                    + " using port " + this.portNumber);
        }
    } catch (Exception e) {
        //System.out.println(e.getMessage());
    }
}

From source file:edu.uci.ics.hyracks.yarn.am.HyracksYarnApplicationMaster.java

private void setupHeartbeats() {
    long heartbeatInterval = config.getLong(YarnConfiguration.RM_AM_EXPIRY_INTERVAL_MS,
            YarnConfiguration.DEFAULT_RM_AM_EXPIRY_INTERVAL_MS);
    System.err.println("Heartbeat interval: " + heartbeatInterval);
    heartbeatInterval = Math.min(heartbeatInterval, 1000);
    System.err.println("Heartbeat interval: " + heartbeatInterval);
    timer.schedule(new TimerTask() {
        @Override/*from  w  w w.  j a  v a  2s  .c om*/
        public void run() {
            AllocateRequest hb = Records.newRecord(AllocateRequest.class);
            populateAllocateRequest(hb);
            hb.setApplicationAttemptId(amrmc.getApplicationAttemptId());
            hb.setProgress(0);
            try {
                AllocateResponse allocateResponse = amrmc.getAMRMProtocol().allocate(hb);
                List<Container> allocatedContainers = allocateResponse.getAMResponse().getAllocatedContainers();
                List<ContainerStatus> completedContainers = allocateResponse.getAMResponse()
                        .getCompletedContainersStatuses();
                processAllocation(allocatedContainers, completedContainers);
            } catch (YarnRemoteException e) {
                e.printStackTrace();
            }
        }
    }, 0, heartbeatInterval);
}

From source file:com.bt.aloha.sipp.SippEngineTestHelper.java

private void setUpSipp(String scenarioName, File directory, boolean respondToOriginatingAddress)
        throws IOException {

    // Give some time to settle between sipp calls.
    try {/*  w w w . j  av a2 s.  co  m*/
        Thread.sleep(TWO_THOUSAND);
    } catch (InterruptedException e) {
    }

    Properties props = new Properties();
    props.load(getClass().getResourceAsStream("/sipp.properties"));

    final String sippPath = props.getProperty("sipp.home") + "/sipp";
    String localIpAddress = setIpAddress(props.getProperty("sip.stack.ip.address.pattern"));
    port = Integer.parseInt(props.getProperty("sipp.local.port"));
    String localPortOption = props.getProperty("sipp.local.port") == null ? "" : String.format("-p %s", port);
    String remoteAddressOption = respondToOriginatingAddress ? ""
            : String.format("-rsa %s:%s", localIpAddress, props.getProperty("sip.stack.port"));
    String runTimesOption = "-m 1";
    String remoteAddressPort = respondToOriginatingAddress ? localIpAddress
            : String.format("%s:%s", localIpAddress, props.getProperty("sip.stack.port"));
    String cmdLine = String.format("%s %s %s %s %s %s", sippPath, remoteAddressOption, runTimesOption,
            scenarioName, remoteAddressPort, localPortOption);
    log.debug(cmdLine);

    System.out.println("COMMAND LINE:");
    System.out.println("cd " + directory.getAbsolutePath());
    System.out.println(cmdLine);
    process = Runtime.getRuntime().exec(cmdLine, null, directory);

    final BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final OutputStream out = process.getOutputStream();
    final BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    timer = new Timer(false);
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            process.destroy();
        }

    }, 30000);

    final Object event = new Object();
    new Thread() {
        public void run() {
            try {
                String line;
                while ((line = err.readLine()) != null) {
                    // while (err.ready() && (line = err.readLine()) !=
                    // null) {
                    errSB.append(line);
                }
                err.close();
            } catch (IOException e) {
                log.debug("Unable to read the error stream from sipp", e);
            }
        }
    }.start();

    new Thread() {
        public void run() {
            try {
                String line;
                while ((line = in.readLine()) != null) {
                    // while (in.ready() && (line = in.readLine()) != null)
                    // {
                    if (line.contains("Terminated")) {
                        break;
                    }

                    if (port == -1 && line.contains("Scenario Screen")) {
                        line = in.readLine();
                        String pattern;
                        int group;

                        if (line.contains("Transport")) {
                            pattern = "(\\d+)";
                            group = 1;
                        } else if (line.contains("Remote-host")) {
                            pattern = "(.*?\\ds.*?)(\\d+)";
                            group = 2;
                        } else
                            continue;

                        line = in.readLine();
                        final Pattern pat = Pattern.compile(pattern);
                        Matcher matcher = pat.matcher(line);
                        matcher.find();
                        port = Integer.parseInt(matcher.group(group));

                        synchronized (event) {
                            event.notify();
                        }
                    }
                }
                in.close();
                out.close();
            } catch (IOException e) {
                log.debug("Unable to read the input stream from sipp", e);
            }
        }
    }.start();

    synchronized (event) {
        try {
            event.wait(FIVE_THOUSAND);
        } catch (InterruptedException e) {
        }
    }

    if (port == -1)
        throw new IOException("Error reading sipp port");

    System.out.println("Running sipp at " + getSippAddress());
}