Example usage for java.util Timer schedule

List of usage examples for java.util Timer schedule

Introduction

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

Prototype

public void schedule(TimerTask task, Date time) 

Source Link

Document

Schedules the specified task for execution at the specified time.

Usage

From source file:org.hubiquitus.hapi.client.HClient.java

/**
 * The hAPI sends the hMessage to the hserver which transfer it to the specified actor.
 * The hserver will perform one of the following actions :
 *  (1). If the actor is a channel (ie : #channelName@domain) the hserver will perform a publish operation of the provided hMessage to the channel and send an hMessage with hResult payload containing the published message and cmd name set with hsend to acknowledge publishing only if a timeout value has been provided.
 *  (2). If the actor is either session and payload type is hCommand the server will handle it. In other cases, it will send an hMessage with a hResult error NOT_AUTHORIZED. Only if the timeout is provided.
 *  (3). If the actor is a jid, hserver will relay the message to the relevant actor.
 * @param message : The message to send. Mandatory.
 * @param messageDelegate : If provided, called by the hAPI when the first message refering to current message arrive . Not mandatory.
 *//*  w  w w.  j a v  a2  s  . co m*/
public void send(final HMessage message, final HMessageDelegate messageDelegate) {
    if (this.connectionStatus != ConnectionStatus.CONNECTED) {
        notifyResultError(message.getMsgid(), ResultStatus.NOT_CONNECTED, ErrorMsg.notConn, messageDelegate);
        return;
    }
    if (message == null) {
        notifyResultError(null, ResultStatus.MISSING_ATTR, ErrorMsg.nullMessage, messageDelegate);
        return;
    }
    if (message.getActor() == null) {
        notifyResultError(message.getMsgid(), ResultStatus.MISSING_ATTR, ErrorMsg.missingActor,
                messageDelegate);
        return;
    }
    message.setSent(new Date());
    message.setPublisher(transportOptions.getFullUrn());
    if (message.getTimeout() > 0) {
        // hAPI will do correlation. If no answer within the
        // timeout, a timeout error will be sent.
        if (messageDelegate != null) {
            message.setMsgid(UUID.randomUUID().toString());
            messagesDelegates.put(message.getMsgid(), messageDelegate);

            Timer timeoutTimer = new Timer();
            timeoutTimer.schedule(new TimerTask() {

                @Override
                public void run() {
                    notifyResultError(message.getMsgid(), ResultStatus.EXEC_TIMEOUT, ErrorMsg.timeout, null);
                    messagesDelegates.remove(message.getMsgid());
                }
            }, message.getTimeout());
            timeoutHashtable.put(message.getMsgid(), timeoutTimer);
        } else {
            //when there is no callback, timeout has no sense. delete timeout.
            message.setTimeout(0);
        }
    }
    try {
        transportManager.sendObject(message);
    } catch (Exception e) {
        logger.error("message: ", e);
    }

}

From source file:com.connectsdk.discovery.provider.SSDPDiscoveryProvider.java

public void sendSearch() {
    List<String> killKeys = new ArrayList<String>();

    long killPoint = new Date().getTime() - SSDP_TIMEOUT;

    for (String key : foundServices.keySet()) {
        ServiceDescription service = foundServices.get(key);
        if (service == null || service.getLastDetection() < killPoint) {
            killKeys.add(key);/*from  w  w  w . jav  a  2 s .c  o m*/
        }
    }

    for (String key : killKeys) {
        final ServiceDescription service = foundServices.get(key);

        if (service != null) {
            Util.runOnUI(new Runnable() {

                @Override
                public void run() {
                    for (DiscoveryProviderListener listener : serviceListeners) {
                        listener.onServiceRemoved(SSDPDiscoveryProvider.this, service);
                    }
                }
            });
        }

        if (foundServices.containsKey(key))
            foundServices.remove(key);
    }

    for (JSONObject searchTarget : serviceFilters) {
        SSDPSearchMsg search = null;
        try {
            search = new SSDPSearchMsg(searchTarget.getString("filter"));
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }

        final String message = search.toString();

        Timer timer = new Timer();
        /* Send 3 times like WindowsMedia */
        for (int i = 0; i < 3; i++) {
            TimerTask task = new TimerTask() {

                @Override
                public void run() {
                    try {
                        if (mSSDPSocket != null)
                            mSSDPSocket.send(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            timer.schedule(task, i * 1000);
        }
    }
    ;
}

From source file:org.apache.hadoop.hive.ql.TestTxnCommands.java

/**
 * Writing UTs that need multiple threads is challenging since Derby chokes on concurrent access.
 * This tests that "AND WAIT" actually blocks and responds to interrupt
 * @throws Exception//  w  w  w.  j a  v  a  2 s .  co m
 */
@Test
public void testCompactionBlocking() throws Exception {
    Timer cancelCompact = new Timer("CancelCompactionTimer", false);
    final Thread threadToInterrupt = Thread.currentThread();
    cancelCompact.schedule(new TimerTask() {
        @Override
        public void run() {
            threadToInterrupt.interrupt();
        }
    }, 5000);
    long start = System.currentTimeMillis();
    runStatementOnDriver("alter table " + TestTxnCommands2.Table.ACIDTBL + " compact 'major' AND WAIT");
    //no Worker so it stays in initiated state
    //w/o AND WAIT the above alter table retunrs almost immediately, so the test here to check that
    //> 2 seconds pass, i.e. that the command in Driver actually blocks before cancel is fired
    Assert.assertTrue(System.currentTimeMillis() > start + 2);
}

From source file:com.gochinatv.datasync.util.Shell.java

/**
 * Run a command//  w  w w. jav a2s .co m
 */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    process = builder.start();
    if (timeOutInterval > 0) {
        timeOutTimer = new Timer();
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ignored) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if ((timeOutTimer != null) && !timedOut.get()) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            inReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
        }
        try {
            errReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = System.currentTimeMillis();
    }
}

From source file:com.onebus.view.MainActivity.java

private void exitBy2Click() {
    Timer tExit = null;
    if (isExit == false) {
        isExit = true; // 
        Toast.makeText(this, "??", Toast.LENGTH_SHORT).show();
        tExit = new Timer();
        tExit.schedule(new TimerTask() {

            public void run() {
                isExit = false; // ?
            }//from   w w  w .ja va2s .  c o m
        }, 2000); // 2???
    } else {
        finish();
        System.exit(0);
    }
}

From source file:Model.RaptorUCIEngine.java

/**
 * Connects to the engine. After this method is invoked the engine name,
 * engine author, and options will be populated in this object.
 * /*from  ww w  .  ja v  a2  s. co m*/
 * @return true if connection was successful, false otherwise.
 */
public boolean connect() {
    if (isConnected()) {
        return true;
    }

    resetConnectionState();

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

        @Override
        public void run() {
            logger.error("The engine could not load before timeout of 15 sec!");
            disconnect();
        }

    }, CONNECTION_TIMEOUT);

    try {

        process = new ProcessBuilder(processPath).directory(new File(new File(processPath).getParent()))
                .start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                if (process != null) {
                    logger.info("Destroying UCI Engine");
                    process.destroy();
                }
            }
        });

        in = new BufferedReader(new InputStreamReader(process.getInputStream()), 10000);
        out = new PrintWriter(process.getOutputStream());

        send("uci");

        String currentLine = null;
        while ((currentLine = readLine()) != null) {

            if (currentLine.startsWith("id")) {
                parseIdLine(currentLine);
            } else if (currentLine.startsWith("option ")) {
                parseOptionLine(currentLine);
            } else if (currentLine.startsWith("uciok")) {
                break;
            } else {

            }
        }

        sendAllNonDefaultOptions();
        isReady();

        timer.cancel();

        return true;
    } catch (Throwable t) {
        disconnect();
        return false;
    }
}

From source file:org.apache.hadoop.mapred.util.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }/*from w  w  w . j  a v a  2  s  .com*/
    if (dir != null) {
        builder.directory(this.dir);
    }

    process = builder.start();
    if (timeOutInterval > 0) {
        timeOutTimer = new Timer();
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if ((timeOutTimer != null) && !timedOut.get()) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            inReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
        }
        try {
            errReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = System.currentTimeMillis();
    }
}

From source file:eu.stratosphere.nephele.taskmanager.TaskManager.java

@Override
public void killTaskManager() throws IOException {
    // Kill the entire JVM after a delay of 10ms, so this RPC will finish properly before
    final Timer timer = new Timer();
    final TimerTask timerTask = new TimerTask() {

        @Override/*from  w ww .j  a va  2s. c  o  m*/
        public void run() {
            System.exit(0);
        }
    };

    timer.schedule(timerTask, 10L);
}

From source file:sf.net.experimaestro.server.JsonRPCMethods.java

/**
 * Shutdown the server//from   w  w  w .j  a  va2  s . c  o m
 */
@RPCMethod(help = "Shutdown Experimaestro server")
public boolean shutdown() {
    // Close the scheduler
    scheduler.close();

    // Shutdown jetty (after 1s to allow this thread to finish)
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            boolean stopped = false;
            try {
                server.stop();
                stopped = true;
            } catch (Exception e) {
                LOGGER.error(e, "Could not stop properly jetty");
            }
            if (!stopped)
                synchronized (this) {
                    try {
                        wait(10000);
                    } catch (InterruptedException e) {
                        LOGGER.error(e);
                    }
                    System.exit(1);

                }
        }
    }, 2000);

    // Everything's OK
    return true;
}

From source file:org.eclipse.jubula.client.core.ClientTest.java

/** {@inheritDoc} */
public Map<String, String> requestAutConfigMapFromAgent(String autId) {
    Map<String, String> autConfigMap = null;
    GetAutConfigMapMessage message = new GetAutConfigMapMessage(autId);
    GetAutConfigMapResponseCommand response = new GetAutConfigMapResponseCommand();
    try {/*from w  w w .  jav  a  2  s.c  om*/
        AutAgentConnection.getInstance().request(message, response, REQUEST_CONFIG_MAP_TIMEOUT);
        final AtomicBoolean timeoutFlag = new AtomicBoolean(true);
        final Timer timerTimeout = new Timer();
        timerTimeout.schedule(new TimerTask() {
            public void run() {
                timeoutFlag.set(false);
                timerTimeout.cancel();
            }
        }, REQUEST_CONFIG_MAP_TIMEOUT);
        while (!response.hasReceivedResponse() && timeoutFlag.get()) {
            TimeUtil.delay(200);
            log.info(Messages.WaitingForAutConfigMapFromAgent);
        }
        autConfigMap = response.getAutConfigMap();
    } catch (NotConnectedException nce) {
        log.error(nce.getLocalizedMessage(), nce);
    } catch (CommunicationException ce) {
        log.error(ce.getLocalizedMessage(), ce);
    }
    return autConfigMap;
}