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.apache.hadoop.chukwa.inputtools.mdl.TorqueInfoProcessor.java

private void getHodJobInfo() throws IOException {
    StringBuffer sb = new StringBuffer();
    sb.append(torqueBinDir).append("/qstat -a");

    String[] getQueueInfoCommand = new String[3];
    getQueueInfoCommand[0] = "ssh";
    getQueueInfoCommand[1] = torqueServer;
    getQueueInfoCommand[2] = sb.toString();

    String command = getQueueInfoCommand[0] + " " + getQueueInfoCommand[1] + " " + getQueueInfoCommand[2];
    ProcessBuilder pb = new ProcessBuilder(getQueueInfoCommand);

    Process p = pb.start();/*w w w. ja v  a  2s . co m*/

    Timer timeout = new Timer();
    TorqueTimerTask torqueTimerTask = new TorqueTimerTask(p, command);
    timeout.schedule(torqueTimerTask, TorqueTimerTask.timeoutInterval * 1000);

    BufferedReader result = new BufferedReader(new InputStreamReader(p.getInputStream()));
    ErStreamHandler errorHandler = new ErStreamHandler(p.getErrorStream(), command, true);
    errorHandler.start();

    String line = null;
    boolean start = false;
    TreeSet<String> jobsInTorque = new TreeSet<String>();
    while ((line = result.readLine()) != null) {
        if (line.startsWith("---")) {
            start = true;
            continue;
        }

        if (start) {
            String[] items = line.split("\\s+");
            if (items.length >= 10) {
                String hodIdLong = items[0];
                String hodId = hodIdLong.split("[.]")[0];
                String userId = items[1];
                String numOfMachine = items[5];
                String status = items[9];
                jobsInTorque.add(hodId);
                if (!currentHodJobs.containsKey(hodId)) {
                    TreeMap<String, String> aJobData = new TreeMap<String, String>();

                    aJobData.put("userId", userId);
                    aJobData.put("numOfMachine", numOfMachine);
                    aJobData.put("traceCheckCount", "0");
                    aJobData.put("process", "0");
                    aJobData.put("status", status);
                    currentHodJobs.put(hodId, aJobData);
                } else {
                    TreeMap<String, String> aJobData = currentHodJobs.get(hodId);
                    aJobData.put("status", status);
                    currentHodJobs.put(hodId, aJobData);
                } // if..else
            }
        }
    } // while

    try {
        errorHandler.join();
    } catch (InterruptedException ie) {
        log.error(ie.getMessage());
    }
    timeout.cancel();

    Set<String> currentHodJobIds = currentHodJobs.keySet();
    Iterator<String> currentHodJobIdsIt = currentHodJobIds.iterator();
    TreeSet<String> finishedHodIds = new TreeSet<String>();
    while (currentHodJobIdsIt.hasNext()) {
        String hodId = currentHodJobIdsIt.next();
        if (!jobsInTorque.contains(hodId)) {
            TreeMap<String, String> aJobData = currentHodJobs.get(hodId);
            String process = aJobData.get("process");
            if (process.equals("0") || process.equals("1")) {
                aJobData.put("status", "C");
            } else {
                finishedHodIds.add(hodId);
            }
        }
    } // while

    Iterator<String> finishedHodIdsIt = finishedHodIds.iterator();
    while (finishedHodIdsIt.hasNext()) {
        String hodId = finishedHodIdsIt.next();
        currentHodJobs.remove(hodId);
    }

}

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

public void testHandleChannelUnavailableWithException_Bug2343() throws Exception {
    int msgCount = 10;
    EmbeddedActiveMq activeMqBroker = new EmbeddedActiveMq();
    String destination = createSafeUniqueId(new Object());
    final Channel channel = createStartableChannel(activeMqBroker, true,
            "testHandleChannelUnavailableWithException_Bug2343", destination);
    JmsTransactedWorkflow workflow = (JmsTransactedWorkflow) channel.getWorkflowList().get(0);
    workflow.setChannelUnavailableWaitInterval(new TimeInterval(1L, TimeUnit.SECONDS));
    workflow.getServiceCollection().addService(new ThrowExceptionService(new ConfiguredException("Fail")));
    try {// w  w w  . ja  va2  s.  c o  m
        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);
    } finally {
        channel.requestClose();
    }
    assertEquals(msgCount, activeMqBroker.messagesOnQueue(destination));
    activeMqBroker.destroy();
}

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);/* ww  w .  ja  va2s .  co  m*/
    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:io.druid.indexing.common.task.AppenderatorDriverRealtimeIndexTask.java

private void setupTimeoutAlert() {
    if (spec.getTuningConfig().getAlertTimeout() > 0) {
        Timer timer = new Timer("RealtimeIndexTask-Timer", true);
        timer.schedule(new TimerTask() {
            @Override//w w w . ja v  a  2s. co  m
            public void run() {
                log.makeAlert(
                        "RealtimeIndexTask for dataSource [%s] hasn't finished in configured time [%d] ms.",
                        spec.getDataSchema().getDataSource(), spec.getTuningConfig().getAlertTimeout()).emit();
            }
        }, spec.getTuningConfig().getAlertTimeout());
    }
}

From source file:com.heneryh.aquanotes.ui.controllers.GraphsFragment.java

public boolean onTouch(View arg0, MotionEvent event) {
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN: // Start gesture
        firstFinger = new PointF(event.getX(), event.getY());
        mode = ONE_FINGER_DRAG;//from w ww.  j a  v  a 2  s. co m
        break;
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_POINTER_UP:
        //When the gesture ends, a thread is created to give inertia to the scrolling and zoom 
        final Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                while (Math.abs(lastScrolling) > 1f || Math.abs(lastZooming - 1) < 1.01) {
                    lastScrolling *= .8; //speed of scrolling damping
                    scroll(lastScrolling);
                    lastZooming += (1 - lastZooming) * .2; //speed of zooming damping
                    zoom(lastZooming);
                    checkBoundaries();
                    try {
                        mySimpleXYPlot.postRedraw();
                    } catch (final InterruptedException e) {
                        e.printStackTrace();
                    }
                    // the thread lives until the scrolling and zooming are imperceptible
                }
            }
        }, 0);

    case MotionEvent.ACTION_POINTER_DOWN: // second finger
        distBetweenFingers = spacing(event);
        // the distance check is done to avoid false alarms
        if (distBetweenFingers > 5f)
            mode = TWO_FINGERS_DRAG;
        break;
    case MotionEvent.ACTION_MOVE:
        if (mode == ONE_FINGER_DRAG) {
            final PointF oldFirstFinger = firstFinger;
            firstFinger = new PointF(event.getX(), event.getY());
            lastScrolling = oldFirstFinger.x - firstFinger.x;
            scroll(lastScrolling);
            lastZooming = (firstFinger.y - oldFirstFinger.y) / mySimpleXYPlot.getHeight();
            if (lastZooming < 0)
                lastZooming = 1 / (1 - lastZooming);
            else
                lastZooming += 1;
            zoom(lastZooming);
            checkBoundaries();
            mySimpleXYPlot.redraw();

        } else if (mode == TWO_FINGERS_DRAG) {
            final float oldDist = distBetweenFingers;
            distBetweenFingers = spacing(event);
            lastZooming = oldDist / distBetweenFingers;
            zoom(lastZooming);
            checkBoundaries();
            mySimpleXYPlot.redraw();
        }
        break;
    }
    return true;
}

From source file:multiplayer.pong.client.LobbyFrame.java

private void handleSockets() {
    socket.on("userConnected", new Emitter.Listener() {
        @Override/* w  ww .ja  v  a  2  s  .  c om*/
        public void call(Object... arg0) {
            String username = (String) arg0[0];
            getConnectedFriends();
            if (connectedFriends.contains(username))
                appendMessage("Votre ami " + username + " vient de se connecter!\n", null);
            refresh();
        }
    }).on("connectedPlayers", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            JSONArray players = (JSONArray) arg0[0];
            Vector<String> online = new Vector<String>();
            try {
                for (int i = 0; i < players.length(); i++) {
                    online.add(players.getJSONObject(i).getString("username"));
                }
            } catch (JSONException e) {
            }
            connectedPlayers = online;
            getConnectedFriends();
            refresh();
        }
    }).on("getMessage", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            JSONObject data = (JSONObject) arg0[0];
            try {
                appendMessage(data.getString("from") + ": " + data.getString("message") + "\n", null);
            } catch (JSONException e) {
            }
        }
    }).on("friendRequest", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            String from = (String) arg0[0];
            displayNotification("Vouz avez une demande d'ajout de " + from + "\n");
            displayHelp("  >> Utilisez la commande '/accepterAmi " + from + "' pour confirmer la demande.\n");
        }
    }).on("friendRequestAck", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            String username = (String) arg0[0];
            displayNotification(username + " est maintenant votre ami.\n");
            displayHelp("Invitez le  une partie en tapant: '/challenge " + username + "'\n");
        }
    }).on("challenge", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            String username = (String) arg0[0];
            displayWarning(username + " vous invite  une partie de Pong\n");
            displayHelp("Tapez '/accepter " + username + "' pour joueur contre lui\n" + "ou '/refuser "
                    + username + "' pour refuser\n");
        }
    }).on("challengeAck", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            JSONObject data = (JSONObject) arg0[0];
            try {
                String opponent = data.getString("opponent");
                if (!data.getBoolean("accepted")) {
                    displayWarning(opponent + " a refus votre dfi.\n");
                } else {
                    // Start the game
                    daoGames.startGame(SocketHandler.username, opponent);
                    SocketHandler.startGame(opponent);
                }
            } catch (JSONException e) {
            }
        }
    }).on("startGame", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            JSONObject data = (JSONObject) arg0[0];
            try {
                String player1 = data.getString("player1");
                String player2 = data.getString("player2");
                if (SocketHandler.username.equals(player1) || SocketHandler.username.equals(player2)) {
                    socket.emit("joinRoom", player1);
                    displayWarning("La partie va commencer dans 5 secondes...\n");
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        String opponent = SocketHandler.username.equals(player1) ? player2 : player1;
                        String location = SocketHandler.username.equals(player1) ? "home" : "away";

                        public void run() {
                            Pong game = new Pong(location, opponent);
                        }
                    }, 5000);
                } else {
                    displayNotification("Un dfi a commenc: " + player1 + " vs " + player2 + "\n");
                }
            } catch (JSONException e) {
            }
        }
    }).on("userDisconnected", new Emitter.Listener() {
        @Override
        public void call(Object... arg0) {
            String username = (String) arg0[0];
            daoGames.cancelRequest(username, null);
            if (connectedFriends.contains(username))
                appendMessage("Votre ami " + username + " vient de se dconnecter!\n", null);
            connectedPlayers.remove(username);
            getConnectedFriends();
            refresh();
        }
    });
}

From source file:com.nbplus.vbroadlauncher.RealtimeBroadcastActivity.java

@Override
public void showText2SpeechAlertDialog() {
    final AlertDialog dialog = new AlertDialog.Builder(this).setMessage(R.string.alert_tts_message)
            //.setTitle(R.string.alert_network_title)
            .setCancelable(true)/*from  w  w  w.j ava  2s. co  m*/
            .setNegativeButton(R.string.alert_tts_btn_settings, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    userInteraction = true;
                    Intent ttsIntent = new Intent();
                    ttsIntent.setAction(Settings.ACTION_SETTINGS);
                    startActivity(ttsIntent);
                }
            }).setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.dismiss();
                    finishActivity();
                    userInteraction = true;
                }
            }).show();
    final Timer t = new Timer();
    t.schedule(new TimerTask() {
        public void run() {
            if (userInteraction == false) {
                dialog.dismiss(); // when the task active then close the dialog
                finishActivity();
            }
            t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
        }
    }, 10000); // after 2 second (or 2000 miliseconds), the task will be active.
}

From source file:org.apache.hadoop.chukwa.inputtools.mdl.TorqueInfoProcessor.java

private boolean loadTraceJobData(String hodId) throws IOException, SQLException {
    TreeMap<String, String> aJobData = currentHodJobs.get(hodId);
    String userId = aJobData.get("userId");
    String process = aJobData.get("process");

    StringBuffer sb = new StringBuffer();
    sb.append(torqueBinDir).append("/tracejob -n 10 -l -m -s ").append(hodId);
    String[] traceJobCommand = new String[3];
    traceJobCommand[0] = "ssh";
    traceJobCommand[1] = torqueServer;//  w ww .j  a  v  a  2 s  .  c  o m
    traceJobCommand[2] = sb.toString();

    String command = traceJobCommand[0] + " " + traceJobCommand[1] + " " + traceJobCommand[2];
    ProcessBuilder pb = new ProcessBuilder(traceJobCommand);

    Process p = pb.start();

    Timer timeout = new Timer();
    TorqueTimerTask torqueTimerTask = new TorqueTimerTask(p, command);
    timeout.schedule(torqueTimerTask, TorqueTimerTask.timeoutInterval * 1000);

    BufferedReader result = new BufferedReader(new InputStreamReader(p.getInputStream()));
    ErStreamHandler errorHandler = new ErStreamHandler(p.getErrorStream(), command, false);
    errorHandler.start();
    String line = null;
    String exit_status = null;
    String hosts = null;
    long timeQueued = -1;
    long startTimeValue = -1;
    long endTimeValue = -1;
    boolean findResult = false;

    while ((line = result.readLine()) != null && !findResult) {
        if (line.indexOf("end") >= 0 && line.indexOf("Exit_status") >= 0 && line.indexOf("qtime") >= 0) {
            TreeMap<String, String> jobData = new TreeMap<String, String>();
            String[] items = line.split("\\s+");
            for (int i = 0; i < items.length; i++) {
                String[] items2 = items[i].split("=");
                if (items2.length >= 2) {
                    jobData.put(items2[0], items2[1]);
                }

            }
            String startTime = jobData.get("ctime");
            startTimeValue = Long.valueOf(startTime);
            startTimeValue = startTimeValue - startTimeValue % (60);
            Timestamp startTimedb = new Timestamp(startTimeValue * 1000);

            String queueTime = jobData.get("qtime");
            long queueTimeValue = Long.valueOf(queueTime);

            String sTime = jobData.get("start");
            long sTimeValue = Long.valueOf(sTime);

            timeQueued = sTimeValue - queueTimeValue;

            String endTime = jobData.get("end");
            endTimeValue = Long.valueOf(endTime);
            endTimeValue = endTimeValue - endTimeValue % (60);
            Timestamp endTimedb = new Timestamp(endTimeValue * 1000);

            exit_status = jobData.get("Exit_status");
            hosts = jobData.get("exec_host");
            String[] items2 = hosts.split("[+]");
            int num = 0;
            for (int i = 0; i < items2.length; i++) {
                String machinetemp = items2[i];
                if (machinetemp.length() >= 3) {
                    String machine = items2[i].substring(0, items2[i].length() - 2);
                    StringBuffer data = new StringBuffer();
                    data.append("HodId=").append(hodId);
                    data.append(", Machine=").append(machine);
                    if (domain != null) {
                        data.append(".").append(domain);
                    }
                    log.info(data.toString());
                    num++;
                }
            }

            StringBuffer data = new StringBuffer();
            data.append("HodID=").append(hodId);
            data.append(", UserId=").append(userId);
            data.append(", Status=").append(exit_status);
            data.append(", TimeQueued=").append(timeQueued);
            data.append(", StartTime=").append(startTimedb);
            data.append(", EndTime=").append(endTimedb);
            data.append(", NumOfMachines=").append(num);
            log.info(data.toString());
            findResult = true;
            log.debug(" hod info for job " + hodId + " has been loaded ");
        } // if

    } // while

    try {
        errorHandler.join();
    } catch (InterruptedException ie) {
        log.error(ie.getMessage());
    }

    timeout.cancel();
    boolean tracedone = false;
    if (!findResult) {

        String traceCheckCount = aJobData.get("traceCheckCount");
        int traceCheckCountValue = Integer.valueOf(traceCheckCount);
        traceCheckCountValue = traceCheckCountValue + 1;
        aJobData.put("traceCheckCount", String.valueOf(traceCheckCountValue));

        log.debug("did not find tracejob info for job " + hodId + ", after " + traceCheckCountValue
                + " times checking");
        if (traceCheckCountValue >= 2) {
            tracedone = true;
        }
    }
    boolean finished = findResult | tracedone;
    return finished;
}

From source file:org.apache.hadoop.chukwa.inputtools.mdl.TorqueInfoProcessor.java

private boolean loadQstatData(String hodId) throws IOException, SQLException {
    TreeMap<String, String> aJobData = currentHodJobs.get(hodId);
    String userId = aJobData.get("userId");

    StringBuffer sb = new StringBuffer();
    sb.append(torqueBinDir).append("/qstat -f -1 ").append(hodId);
    String[] qstatCommand = new String[3];
    qstatCommand[0] = "ssh";
    qstatCommand[1] = torqueServer;// w  w w.  j a va 2 s.  c om
    qstatCommand[2] = sb.toString();

    String command = qstatCommand[0] + " " + qstatCommand[1] + " " + qstatCommand[2];
    ProcessBuilder pb = new ProcessBuilder(qstatCommand);
    Process p = pb.start();

    Timer timeout = new Timer();
    TorqueTimerTask torqueTimerTask = new TorqueTimerTask(p, command);
    timeout.schedule(torqueTimerTask, TorqueTimerTask.timeoutInterval * 1000);

    BufferedReader result = new BufferedReader(new InputStreamReader(p.getInputStream()));
    ErStreamHandler errorHandler = new ErStreamHandler(p.getErrorStream(), command, false);
    errorHandler.start();
    String line = null;
    String hosts = null;
    long startTimeValue = -1;
    long endTimeValue = Calendar.getInstance().getTimeInMillis();
    long executeTimeValue = Calendar.getInstance().getTimeInMillis();
    boolean qstatfinished;

    while ((line = result.readLine()) != null) {
        if (line.indexOf("ctime") >= 0) {
            String startTime = line.split("=")[1].trim();
            // Tue Sep 9 23:44:29 2008
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy");
            Date startTimeDate;
            try {
                startTimeDate = sdf.parse(startTime);
                startTimeValue = startTimeDate.getTime();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        if (line.indexOf("mtime") >= 0) {
            String endTime = line.split("=")[1].trim();
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy");
            Date endTimeDate;
            try {
                endTimeDate = sdf.parse(endTime);
                endTimeValue = endTimeDate.getTime();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        if (line.indexOf("etime") >= 0) {
            String executeTime = line.split("=")[1].trim();
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy");
            Date executeTimeDate;
            try {
                executeTimeDate = sdf.parse(executeTime);
                executeTimeValue = executeTimeDate.getTime();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        if (line.indexOf("exec_host") >= 0) {
            hosts = line.split("=")[1].trim();
        }
    }

    if (hosts != null && startTimeValue >= 0) {
        String[] items2 = hosts.split("[+]");
        int num = 0;
        for (int i = 0; i < items2.length; i++) {
            String machinetmp = items2[i];
            if (machinetmp.length() > 3) {
                String machine = items2[i].substring(0, items2[i].length() - 2);
                StringBuffer data = new StringBuffer();
                data.append("HodId=").append(hodId);
                data.append(", Machine=").append(machine);
                if (domain != null) {
                    data.append(".").append(domain);
                }
                log.info(data);
                num++;
            }
        }
        Timestamp startTimedb = new Timestamp(startTimeValue);
        Timestamp endTimedb = new Timestamp(endTimeValue);
        StringBuffer data = new StringBuffer();
        long timeQueued = executeTimeValue - startTimeValue;
        data.append("HodID=").append(hodId);
        data.append(", UserId=").append(userId);
        data.append(", StartTime=").append(startTimedb);
        data.append(", TimeQueued=").append(timeQueued);
        data.append(", NumOfMachines=").append(num);
        data.append(", EndTime=").append(endTimedb);
        log.info(data);
        qstatfinished = true;

    } else {

        qstatfinished = false;
    }

    try {
        errorHandler.join();
    } catch (InterruptedException ie) {
        log.error(ie.getMessage());
    }
    result.close();
    timeout.cancel();

    return qstatfinished;
}

From source file:org.openhab.binding.amazonechocontrol.internal.WebSocketConnection.java

void initPongTimeoutTimer() {
    clearPongTimeoutTimer();//from   w ww  .  ja  v a  2  s. com
    Timer pongTimeoutTimer = new Timer();
    this.pongTimeoutTimer = pongTimeoutTimer;
    pongTimeoutTimer.schedule(new TimerTask() {

        @Override
        public void run() {
            close();
        }
    }, 60000);
}