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 firstTime, long period) 

Source Link

Document

Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.

Usage

From source file:gtu._work.etc.EnglishTester.java

void startNow() {
    final StringBuilder currentTime = new StringBuilder();
    currentTime.append(System.currentTimeMillis());

    wordsList = new ArrayList<String>();
    pickProp = new Properties();

    if (picOnly.isSelected()) {
        filterHasPicProp();//ww w  . j a  v  a  2  s .  c  om
    }

    for (Enumeration<?> enu = englishProp.propertyNames(); enu.hasMoreElements();) {
        String key = (String) enu.nextElement();
        String value = englishProp.getProperty(key);
        wordsList.add(key);
    }
    wordsList = RandomUtil.randomList(wordsList);

    if (sortChkBox.isSelected()) {
        Collections.sort(wordsList);
        ifIsNumberSort(wordsList);
    }

    propCountLabel.setText(String.valueOf(englishProp.size()));
    questionCountLabel.setText(String.valueOf(wordsList.size()));

    // ?
    inputTestTrainer.initQuestion();

    setVisible(false);

    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            // jTabbedPane1.setSelectedIndex(tabSelectedCombo.getSelectedIndex());//
            // 

            if (!EnglishTester.gtu.swing.util.JFrameUtil.isVisible(this)) {
                setVisible(true);
            }

            // ??
            if (currentWordIndex == wordsList.get(0)) {
                return;
            }

            // System.out.println(wordsList);
            if (!wordsList.isEmpty()) {
                String word = wordsList.get(0);

                // 
                setCurrentWord(word);
                // 

                scanPic();
                if (showChineseOption.isSelected()) {
                    setPictureDialogShow(true);
                }

                // 
                resetAnswers(word);
                // 
            } else {
                JCommonUtil._jOptionPane_showMessageDialog_info("words is over");
                timer.cancel();
            }
        }
    }, 0, DELAY_TIME);
}

From source file:com.sveder.cardboardpassthrough.MainActivity.java

private void callMessageTask() {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override//from   w ww .j ava2  s.  c o  m
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        MessageTask getMessageTask = new MessageTask(MainActivity.this);
                        getMessageTask.setMessageLoading(null);
                        getMessageTask.execute(TASKS_URL);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 5000); //execute in every 50000 ms

}

From source file:ca.weblite.jdeploy.JDeploy.java

private void init_old(String commandName) throws IOException {
    try {/*from  w  w  w  . ja v  a  2  s .  co  m*/
        File packageJson = new File(directory, "package.json");
        if (!packageJson.exists()) {
            ProcessBuilder pb = new ProcessBuilder();
            pb.command(npm, "init");
            pb.inheritIO();
            final Process p = pb.start();
            Timer t = new Timer();

            TimerTask tt = new TimerTask() {

                @Override
                public void run() {
                    if (packageJson.exists()) {
                        p.destroy();
                        cancel();
                    }
                }

            };
            t.schedule(tt, new Date(System.currentTimeMillis() + 1000), 1000);

            int code = p.waitFor();

            if (!packageJson.exists() && code != 0) {
                System.err.println("Stopped init because npm init failed");
                System.exit(code);
            }
        }

        String pkgJsonStr = FileUtils.readFileToString(packageJson, "UTF-8");
        if (!pkgJsonStr.contains("shelljs")) {
            System.out.println("Installing shelljs");
            ProcessBuilder pb = new ProcessBuilder();
            pb.inheritIO();
            pb.command(npm, "install", "shelljs", "--save");
            Process p = pb.start();
            int result = p.waitFor();
            if (result != 0) {
                System.err.println("Failed to install shelljs");
                System.exit(result);
            }
        }

        // For some reason it never sticks in the package.json file the first time
        pkgJsonStr = FileUtils.readFileToString(packageJson, "UTF-8");
        if (!pkgJsonStr.contains("shelljs")) {
            System.out.println("Installing shelljs");
            ProcessBuilder pb = new ProcessBuilder();
            pb.inheritIO();
            pb.command(npm, "install", "shelljs", "--save");
            Process p = pb.start();
            int result = p.waitFor();
            if (result != 0) {
                System.err.println("Failed to install shelljs");
                System.exit(result);
            }
        }

        JSONParser parser = new JSONParser();
        Map contents = parser.parseJSON(new StringReader(pkgJsonStr));
        if (commandName == null) {
            commandName = (String) contents.get("name");
        }

        if (!contents.containsKey("bin")) {
            contents.put("bin", new HashMap());
        }
        Map bins = (Map) contents.get("bin");

        if (!bins.values().contains(getBinDir() + "/jdeploy.js")) {
            contents.put("preferGlobal", true);
            bins.put(commandName, getBinDir() + "/jdeploy.js");
            Result res = Result.fromContent(contents);
            FileUtils.writeStringToFile(packageJson, res.toString(), "UTF-8");
        }

        if (!contents.containsKey("files")) {
            contents.put("files", new ArrayList());
        }
        List files = (List) contents.get("files");
        if (!files.contains(getBinDir())) {
            files.add(getBinDir());
            Result res = Result.fromContent(contents);
            FileUtils.writeStringToFile(packageJson, res.toString(), "UTF-8");
        }

    } catch (InterruptedException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.alivenet.dmvtaxi.fragment.FragmentArriveDriver.java

public void callBackgroundService(final double latitude, final double longitude) {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override// w  w  w.j a  v a2  s. c o  m
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {

                        if (latitude != 0.0d && longitude != 0.0d) {

                            Intent intent = new Intent(getActivity(), BackgroundService.class);
                            intent.putExtra("userid", mUserId);
                            intent.putExtra("lat", String.valueOf(latitude));
                            intent.putExtra("long", String.valueOf(longitude));
                            getActivity().startService(intent);
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 5000);
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.GerritServer.java

/**
 * Server to sleep. This method returns actual connection status is changed or timeout.
 * Used by jelly.//from w  w  w.  j a  va  2 s. c o m
 *
 * @return connection status.
 */
public JSONObject doSleep() {
    Timer timer = new Timer();
    try {
        stopConnection();

        final CountDownLatch responseLatch = new CountDownLatch(RESPONSE_COUNT);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (gerritConnectionListener == null || !gerritConnectionListener.isConnected()) {
                    responseLatch.countDown();
                }
            }
        }, RESPONSE_INTERVAL_MS, RESPONSE_INTERVAL_MS);

        if (responseLatch.await(RESPONSE_TIMEOUT_S, TimeUnit.SECONDS)) {
            setConnectionResponse(STOP_SUCCESS);
        } else {
            throw new InterruptedException("time out.");
        }
    } catch (Exception ex) {
        setConnectionResponse(STOP_FAILURE);
        logger.error("Could not stop connection. ", ex);
    }
    timer.cancel();

    JSONObject obj = new JSONObject();
    String status = "down";
    if (gerritConnectionListener != null) {
        if (gerritConnectionListener.isConnected()) {
            status = "up";
        }
    }
    obj.put("status", status);
    return obj;
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.GerritServer.java

/**
 * Wakeup server. This method returns after actual connection status is changed or timeout.
 * Used by jelly./*from  ww w  .  ja  v a2s  .  co m*/
 *
 * @return connection status.
 */
public JSONObject doWakeup() {
    Timer timer = new Timer();
    try {
        startConnection();

        final CountDownLatch responseLatch = new CountDownLatch(RESPONSE_COUNT);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (gerritConnectionListener != null && gerritConnectionListener.isConnected()) {
                    responseLatch.countDown();
                }
            }
        }, RESPONSE_INTERVAL_MS, RESPONSE_INTERVAL_MS);

        if (responseLatch.await(RESPONSE_TIMEOUT_S, TimeUnit.SECONDS)) {
            timeoutWakeup = false;
            setConnectionResponse(START_SUCCESS);
        } else {
            timeoutWakeup = true;
            throw new InterruptedException("time out.");
        }
    } catch (Exception ex) {
        setConnectionResponse(START_FAILURE);
        logger.error("Could not start connection. ", ex);
    }
    timer.cancel();

    JSONObject obj = new JSONObject();
    String status = "down";
    if (gerritConnectionListener != null) {
        if (gerritConnectionListener.isConnected()) {
            status = "up";
        }
    }
    obj.put("status", status);
    return obj;
}

From source file:gate.util.reporting.PRTimeReporter.java

/**
 * Calls store, calculate and printReport for generating the actual report.
 *///from   w  w w.j  a  va 2 s.co  m
@SuppressWarnings("unchecked")
private void generateReport() throws BenchmarkReportInputFileFormatException {
    Timer timer = null;
    try {
        TimerTask task = new FileWatcher(getBenchmarkFile()) {
            @Override
            protected void onChange(File file) throws BenchmarkReportExecutionException {
                throw new BenchmarkReportExecutionException(
                        getBenchmarkFile() + " file has been modified while generating the report.");
            }
        };
        timer = new Timer();
        // repeat the check every second
        timer.schedule(task, new Date(), 1000);

        Object report1Container1 = store(getBenchmarkFile());
        Object report1Container2 = calculate(report1Container1);
        if (getSortOrder().equalsIgnoreCase("time_taken")) {
            report1Container2 = sortReport((LinkedHashMap<String, Object>) report1Container2);
        }
        if (reportFile == null) {
            reportFile = new File(System.getProperty("java.io.tmpdir"),
                    "report." + ((printMedia.equals(MEDIA_HTML)) ? "html" : "txt"));
        }
        printReport(report1Container2, reportFile);
    } finally {
        if (timer != null) {
            timer.cancel();
        }
    }
}

From source file:com.xiaoyu.DoctorHelp.chat.chatuidemo.adapter.MessageAdapter.java

/**
 * ?//from   w  ww.j  ava2  s  .  c  o  m
 *
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleFileMessage(final EMMessage message, final ViewHolder holder, int position,
        View convertView) {
    final NormalFileMessageBody fileMessageBody = (NormalFileMessageBody) message.getBody();
    final String filePath = fileMessageBody.getLocalUrl();
    holder.tv_file_name.setText(fileMessageBody.getFileName());
    holder.tv_file_size.setText(TextFormater.getDataSize(fileMessageBody.getFileSize()));
    holder.ll_container.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View view) {
            File file = new File(filePath);
            if (file != null && file.exists()) {
                // 
                FileUtils.openFile(file, (Activity) context);
            } else {
                // 
                context.startActivity(
                        new Intent(context, ShowNormalFileActivity.class).putExtra("msgbody", fileMessageBody));
            }
            if (message.direct == EMMessage.Direct.RECEIVE && !message.isAcked
                    && message.getChatType() != ChatType.GroupChat
                    && message.getChatType() != ChatType.ChatRoom) {
                try {
                    EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
                    message.isAcked = true;
                } catch (EaseMobException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    });
    String st1 = context.getResources().getString(R.string.Have_downloaded);
    String st2 = context.getResources().getString(R.string.Did_not_download);
    if (message.direct == EMMessage.Direct.RECEIVE) { // ?
        EMLog.d(TAG, "it is receive msg");
        File file = new File(filePath);
        if (file != null && file.exists()) {
            holder.tv_file_download_state.setText(st1);
        } else {
            holder.tv_file_download_state.setText(st2);
        }
        return;
    }

    // until here, deal with send voice msg
    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.INVISIBLE);
        holder.tv.setVisibility(View.INVISIBLE);
        holder.staus_iv.setVisibility(View.INVISIBLE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.INVISIBLE);
        holder.tv.setVisibility(View.INVISIBLE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.INVISIBLE);
                            holder.tv.setVisibility(View.INVISIBLE);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.INVISIBLE);
                            holder.tv.setVisibility(View.INVISIBLE);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity,
                                    activity.getString(R.string.send_fail)
                                            + activity.getString(R.string.connect_failuer_toast),
                                    Toast.LENGTH_SHORT).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        // ???
        sendMsgInBackground(message, holder);
    }

}

From source file:maimeng.yodian.app.client.android.chat.adapter.MessageAdapter.java

/**
 * ?/*from ww w  .j  a va  2s. c om*/
 *
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleImageMessage(final EMMessage message, final ViewHolder holder, final int position,
        View convertView) {
    holder.pb.setTag(position);
    holder.iv.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            activity.startActivityForResult(
                    (new Intent(activity, ContextMenu.class)).putExtra("position", position).putExtra("type",
                            EMMessage.Type.IMAGE.ordinal()),
                    ChatActivity.REQUEST_CODE_CONTEXT_MENU, new Bundle());
            return true;
        }
    });

    // ??
    if (message.direct == EMMessage.Direct.RECEIVE) {
        // "it is receive msg";
        if (message.status == EMMessage.Status.INPROGRESS) {
            // "!!!! back receive";
            holder.iv.setImageResource(R.mipmap.default_image);
            showDownloadImageProgress(message, holder);
            // downloadImage(message, holder);
        } else {
            // "!!!! not back receive, show image directly");
            holder.pb.setVisibility(View.GONE);
            holder.tv.setVisibility(View.GONE);
            holder.iv.setImageResource(R.mipmap.default_image);
            ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
            if (imgBody.getLocalUrl() != null) {
                // String filePath = imgBody.getLocalUrl();
                String remotePath = imgBody.getRemoteUrl();
                String filePath = ImageUtils.getImagePath(remotePath);
                String thumbRemoteUrl = imgBody.getThumbnailUrl();
                if (TextUtils.isEmpty(thumbRemoteUrl) && !TextUtils.isEmpty(remotePath)) {
                    thumbRemoteUrl = remotePath;
                }
                String thumbnailPath = ImageUtils.getThumbnailImagePath(thumbRemoteUrl);
                showImageView(thumbnailPath, holder.iv, filePath, imgBody.getRemoteUrl(), message);
            }
        }
        return;
    }

    // ???
    // process send message
    // send pic, show the pic directly
    ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
    String filePath = imgBody.getLocalUrl();
    if (filePath != null && new File(filePath).exists()) {
        showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, null, message);
    } else {
        showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, IMAGE_DIR, message);
    }

    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.GONE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        holder.staus_iv.setVisibility(View.GONE);
        holder.pb.setVisibility(View.VISIBLE);
        holder.tv.setVisibility(View.VISIBLE);
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
                            // message.setProgress(0);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity,
                                    activity.getString(R.string.send_fail)
                                            + activity.getString(R.string.connect_failuer_toast),
                                    Toast.LENGTH_SHORT).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        sendPictureMessage(message, holder);
    }
}

From source file:com.xiaoyu.DoctorHelp.chat.chatuidemo.adapter.MessageAdapter.java

/**
 * ?//from   w w w.  j  a v a  2  s .c om
 *
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleImageMessage(final EMMessage message, final ViewHolder holder, final int position,
        View convertView) {
    holder.pb.setTag(position);
    holder.iv.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            activity.startActivityForResult((new Intent(activity, ContextMenu.class))
                    .putExtra("position", position).putExtra("type", EMMessage.Type.IMAGE.ordinal()),
                    ChatActivity.REQUEST_CODE_CONTEXT_MENU);
            return true;
        }
    });

    // ??
    if (message.direct == EMMessage.Direct.RECEIVE) {
        // "it is receive msg";
        if (message.status == EMMessage.Status.INPROGRESS) {
            // "!!!! back receive";
            holder.iv.setImageResource(R.drawable.default_image);
            showDownloadImageProgress(message, holder);
            // downloadImage(message, holder);
        } else {
            // "!!!! not back receive, show image directly");
            holder.pb.setVisibility(View.GONE);
            holder.tv.setVisibility(View.GONE);
            holder.iv.setImageResource(R.drawable.default_image);
            ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
            if (imgBody.getLocalUrl() != null) {
                // String filePath = imgBody.getLocalUrl();
                String remotePath = imgBody.getRemoteUrl();
                String filePath = ImageUtils.getImagePath(remotePath);
                String thumbRemoteUrl = imgBody.getThumbnailUrl();
                String thumbnailPath = ImageUtils.getThumbnailImagePath(thumbRemoteUrl);
                showImageView(thumbnailPath, holder.iv, filePath, imgBody.getRemoteUrl(), message);
            }
        }
        return;
    }

    // ???
    // process send message
    // send pic, show the pic directly
    ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
    String filePath = imgBody.getLocalUrl();
    if (filePath != null && new File(filePath).exists()) {
        showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, null, message);
    } else {
        showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, IMAGE_DIR, message);
    }

    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.GONE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        holder.staus_iv.setVisibility(View.GONE);
        holder.pb.setVisibility(View.VISIBLE);
        holder.tv.setVisibility(View.VISIBLE);
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
                            // message.setProgress(0);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity,
                                    activity.getString(R.string.send_fail)
                                            + activity.getString(R.string.connect_failuer_toast),
                                    Toast.LENGTH_SHORT).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        sendPictureMessage(message, holder);
    }
}