Example usage for java.util Timer Timer

List of usage examples for java.util Timer Timer

Introduction

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

Prototype

public Timer() 

Source Link

Document

Creates a new timer.

Usage

From source file:mina.UnsyncClientSupport.java

/**
 * ????FTS/*from w w w . ja  v a  2s  . c  om*/
 * 
 * @param node
 * @param message
 * @throws CommunicationException
 * @throws InterruptedException
 * @throws InterruptedException
 * @throws IOException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void send(String msg) throws InterruptedException, IOException {
    // EPS ?? CPS ??????
    byte[] message;
    List messages = new ArrayList();
    try {
        message = FileUtils.readFileToByteArray(new File("src/Eps2CpsAtmInquireReq"));
        message = Arrays.copyOf(message, message.length - 1);
        messages.add(message);

        message = FileUtils.readFileToByteArray(new File("src/Eps2CpsAuthCancelReq"));
        message = Arrays.copyOf(message, message.length - 1);
        messages.add(message);

        message = FileUtils.readFileToByteArray(new File("src/Eps2CpsAuthReq"));
        message = Arrays.copyOf(message, message.length - 1);
        messages.add(message);

        message = FileUtils.readFileToByteArray(new File("src/Eps2CpsPosInquireReq"));
        message = Arrays.copyOf(message, message.length - 1);
        messages.add(message);

        message = FileUtils.readFileToByteArray(new File("src/Eps2CpsWithdrawReq"));
        message = Arrays.copyOf(message, message.length - 1);
        messages.add(message);

        for (int i = 0; i < messages.size(); i++) {
            byte[] tmp = (byte[]) messages.get(i);
            byte[] data = CommonUtils.update(tmp, false);
            messages.set(i, data);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    timer = new Timer();
    timer.schedule(new SendMessageTask(messages), 0, 1000);
}

From source file:com.yahala.ui.LoginActivitySmsView.java

@Override
public void setParams(Bundle params) {
    codeField.setText("");
    OSUtilities.setWaitingForSms(true);/*from  ww w . j a  va 2 s.  co m*/
    NotificationCenter.getInstance().addObserver(this, 998);
    currentParams = params;
    waitingForSms = true;
    String phone = params.getString("phone");
    requestPhone = params.getString("phoneFormated");
    phoneHash = params.getString("phoneHash");

    registered = params.getString("registered");
    FileLog.e("yahala",
            requestPhone + "  phoneHash:" + phoneHash + "registered" + params.getString("registered"));
    time = params.getInt("calltime");

    String number = PhoneFormat.getInstance().format(phone);
    confirmTextView.setText(Html.fromHtml(String.format(
            ApplicationLoader.applicationContext.getResources().getString(R.string.SentSmsCode) + " <b>%s</b>",
            number)));

    OSUtilities.showKeyboard(codeField);
    codeField.requestFocus();

    try {
        synchronized (timerSync) {
            if (timeTimer != null) {
                timeTimer.cancel();
                timeTimer = null;
            }
        }
    } catch (Exception e) {
        FileLog.e("yahala", e);
    }
    timeText.setText(String.format("%s 1:00",
            ApplicationLoader.applicationContext.getResources().getString(R.string.CallText)));
    lastCurrentTime = System.currentTimeMillis();
    timeTimer = new Timer();
    timeTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            double currentTime = System.currentTimeMillis();
            double diff = currentTime - lastCurrentTime;
            time -= diff;
            lastCurrentTime = currentTime;
            Utilities.RunOnUIThread(new Runnable() {
                @Override
                public void run() {
                    if (time >= 1000) {
                        int minutes = time / 1000 / 60;
                        int seconds = time / 1000 - minutes * 60;
                        timeText.setText(String.format("%s %d:%02d", ApplicationLoader.applicationContext
                                .getResources().getString(R.string.CallText), minutes, seconds));
                    } else {
                        timeText.setText(ApplicationLoader.applicationContext.getResources()
                                .getString(R.string.Calling));
                        synchronized (timerSync) {
                            if (timeTimer != null) {
                                timeTimer.cancel();
                                timeTimer = null;
                            }
                        }
                        TLRPC.TL_auth_sendCall req = new TLRPC.TL_auth_sendCall();
                        req.phone_number = requestPhone;
                        req.phone_code_hash = phoneHash;
                    }
                }
            });
        }
    }, 0, 1000);
    sendSmsRequest();
}

From source file:com.halseyburgund.rwframework.core.RWStreamAssetsTracker.java

/**
 * Starts tracking the assets streamed by the server. This basically
 * handles everything and does an intent broadcast when it estimates
 * the asset being played on the device is changed. I.e. it has passed
 * from the server stream and made it to the front of the audio buffer
 * on the device and the user started hearing it play.
 * //ww  w. j a va2s.c om
 * The project configuration (will be retrieved from the RWService) is
 * used to get the streamMetadataEnabled property to decide if the
 * server will be sending metadata and using this class is possible. The
 * streamMetadataTimerIntervalMSec property specifies the timer interval
 * that will be used.
 * 
 * The broadcasted intent has the following properties:
 * Action: RW.STREAM_METADATA_UPDATED
 * Extra : RW.EXTRA_STREAM_METADATA_CURRENT_ASSET_ID (int)
 * Extra : RW.EXTRA_STREAM_METADATA_PREVIOUS_ASSET_ID (int)
 * Extra : RW.EXTRA_STREAM_METADATA_TITLE (String)
 * 
 * Call stop() when no longer interested in the metadata. This will
 * stop the tracking loop and free some resources.
 */
public void start() {
    if (mMetadataReaderTimer != null) {
        stop();
    }

    RWConfiguration config = mRwService.getConfiguration();

    if ((config != null) && (config.isStreamMetadataEnabled())) {
        if (D) {
            Log.d(TAG, "Starting stream metadata reader", null);
        }
        mMetadataReaderTimer = new Timer();
        updateStreamMetadata(-1, "");
        mMetadataReaderTimer.schedule(new TimerTask() {
            public void run() {
                streamMetadataUpdate();
            }
        }, 0, config.getStreamMetadataTimerIntervalMSec());
    }
}

From source file:main.AddNodeDemo.java

@Override
public void init() {

    //create a graph
    Graph<String, Number> ig = Graphs
            .<String, Number>synchronizedDirectedGraph(new DirectedSparseMultigraph<String, Number>());

    ObservableGraph<String, Number> og = new ObservableGraph<String, Number>(ig);
    og.addGraphEventListener(new GraphEventListener<String, Number>() {

        public void handleGraphEvent(GraphEvent<String, Number> evt) {
            System.err.println("got " + evt);

        }/*  ww  w  .j  a  va 2  s.  c  om*/
    });
    this.g = og;
    //create a graphdraw
    //        layout = new FRLayout2<String,Number>(g);
    //        layout = new SpringLayout<String,Number>(g);
    //        ((FRLayout)layout).setMaxIterations(200);
    layout = new KKLayout<String, Number>(g);

    vv = new VisualizationViewer<String, Number>(layout, new Dimension(600, 600));

    JRootPane rp = this.getRootPane();
    rp.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);

    getContentPane().setLayout(new BorderLayout());
    getContentPane().setBackground(java.awt.Color.lightGray);
    getContentPane().setFont(new Font("Serif", Font.PLAIN, 12));

    vv.getModel().getRelaxer().setSleepTime(500);
    vv.setGraphMouse(new DefaultModalGraphMouse<Number, Number>());

    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String>());
    vv.setForeground(Color.white);

    FontMetrics fm = vv.getFontMetrics(vv.getFont());
    int width = fm.stringWidth(g.toString());

    Transformer<String, Shape> vertexSize = new Transformer<String, Shape>() {
        public Shape transform(String i) {

            Ellipse2D circle = new Ellipse2D.Double(-20, -20, 40, 40);
            // in this case, the vertex is twice as large                
            return circle;
        }

    };

    //        vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller() {
    //            @Override
    //            public String transform(Object v) {
    //
    //                return ((VertexTopology)v).screenName;
    //            }});

    vv.getRenderContext().setVertexShapeTransformer(vertexSize);

    getContentPane().setPreferredSize(new Dimension(1400, 900));
    getContentPane().add(vv);
    switchLayout = new JButton("Switch to SpringLayout");
    //        switchLayout.addActionListener(new ActionListener() {
    //
    //            @SuppressWarnings("unchecked")
    //            public void actionPerformed(ActionEvent ae) {
    //               Dimension d = new Dimension(600,600);
    //                if (switchLayout.getText().indexOf("Spring") > 0) {
    //                    switchLayout.setText("Switch to FRLayout");
    //                    layout = new SpringLayout<String,Number>(g,
    //                        new ConstantTransformer(EDGE_LENGTH));
    //                    layout.setSize(d);
    //                    vv.getModel().setGraphLayout(layout, d);
    //                } else {
    //                    switchLayout.setText("Switch to SpringLayout");
    //                    layout = new FRLayout<String,Number>(g, d);
    //                    vv.getModel().setGraphLayout(layout, d);
    //                }
    //            }
    //        });

    getContentPane().add(switchLayout, BorderLayout.SOUTH);

    timer = new Timer();
}

From source file:com.phonegap.PhoneGap.java

private void init(final String url) {
    commandManager = new CommandManager(this);
    _mainScreen = new MainScreen();
    pushScreen(_mainScreen);//w  w  w . j  ava  2  s  .  c o m
    // Add loading screen and display ASAP
    loadingImage = EncodedImage.getEncodedImageResource(LOADING_IMAGE);
    if (loadingImage != null) {
        // If a loading image exists, add it to the loading field and push it onto the screen stack.
        loadingField.setImage(loadingImage);
        loadingScreen.add(loadingField);
        pushScreen(loadingScreen);
    }
    _mainScreen.addKeyListener(new PhoneGapKeyListener(this));

    // Set up the browser/renderer.
    _renderingSession = RenderingSession.getNewInstance();
    _renderingSession.getRenderingOptions().setProperty(RenderingOptions.CORE_OPTIONS_GUID,
            RenderingOptions.JAVASCRIPT_ENABLED, true);
    _renderingSession.getRenderingOptions().setProperty(RenderingOptions.CORE_OPTIONS_GUID,
            RenderingOptions.JAVASCRIPT_LOCATION_ENABLED, true);
    // Enable nice-looking BlackBerry browser field.
    _renderingSession.getRenderingOptions().setProperty(RenderingOptions.CORE_OPTIONS_GUID, 17000, true);
    PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread(url, null, null, null, this);
    thread.start();
    refreshTimer = new Timer();
    refreshTimer.scheduleAtFixedRate(new TimerRefresh(), 500, 500);
}

From source file:jp.mamesoft.mailsocketchat.Mail.java

public void run() {
    while (true) {
        try {//ww w  .  j  av a 2 s .c o m
            System.out.println("????");
            Properties props = System.getProperties();

            // Get a Session object
            Session session = Session.getInstance(props, null);
            // session.setDebug(true);

            // Get a Store object
            Store store = session.getStore("imaps");

            // Connect
            store.connect("imap.gmail.com", 993, Mailsocketchat.mail_user, Mailsocketchat.mail_pass);
            System.out.println("??????");

            // Open a Folder
            Folder folder = store.getFolder("INBOX");
            if (folder == null || !folder.exists()) {
                System.out.println("IMAP??????");
                System.exit(1);
            }

            folder.open(Folder.READ_WRITE);

            // Add messageCountListener to listen for new messages
            folder.addMessageCountListener(new MessageCountAdapter() {
                public void messagesAdded(MessageCountEvent ev) {
                    Message[] msgs = ev.getMessages();

                    // Just dump out the new messages
                    for (int i = 0; i < msgs.length; i++) {
                        try {
                            System.out.println("?????");
                            InternetAddress addrfrom = (InternetAddress) msgs[i].getFrom()[0];
                            String subject = msgs[i].getSubject();
                            if (subject == null) {
                                subject = "";
                            }

                            Pattern hashtag_p = Pattern.compile("#(.+)");
                            Matcher hashtag_m = hashtag_p.matcher(subject);

                            if (subject.equals("#")) {
                                hashtag = null;
                            } else if (hashtag_m.find()) {
                                hashtag = hashtag_m.group(1);
                            }

                            String comment = msgs[i].getContent().toString().replaceAll("\r\n", " ");
                            comment = comment.replaceAll("\n", " ");
                            comment = comment.replaceAll("\r", " ");
                            JSONObject data = new JSONObject();
                            data.put("comment", comment);
                            if (hashtag != null) {
                                data.put("channel", hashtag);
                            }
                            if (!comment.equals("") && !comment.equals(" ") && !comment.equals("  ")) {
                                Mailsocketchat.socket.emit("say", data);
                                System.out.println("????");
                            }

                            //
                            if (subject.equals("push") || subject.equals("Push")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 2);
                                Mailsocketchat.push = true;
                                Mailsocketchat.repeat = false;
                                Mailsocketchat.address = addrfrom.getAddress();
                                repeatthread.cancel();
                                repeatthread = null;
                                System.out.println("?????");
                            } else if (subject.equals("fetch") || subject.equals("Fetch")
                                    || subject.equals("?")) {
                                Send(addrfrom.getAddress(), 3);
                                Mailsocketchat.push = false;
                                Mailsocketchat.repeat = false;
                                repeatthread.cancel();
                                repeatthread = null;
                                System.out.println("??????");
                            } else if (subject.equals("repeat") || subject.equals("Repeat")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 7);
                                Mailsocketchat.push = false;
                                Mailsocketchat.repeat = true;
                                Mailsocketchat.address = addrfrom.getAddress();
                                if (repeatthread == null) {
                                    repeatthread = new Repeat();
                                    repeat = new Timer();
                                }
                                repeat.schedule(repeatthread, 0, 30 * 1000);
                                System.out.println("?????");
                            } else if (subject.equals("list") || subject.equals("List")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 4);
                            } else if (subject.equals("help") || subject.equals("Help")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 5);
                            } else {
                                if (!Mailsocketchat.push && !Mailsocketchat.repeat) {
                                    Send(addrfrom.getAddress(), 0);
                                } else if (comment.equals("") || comment.equals(" ") || comment.equals("  ")) {
                                    Send(addrfrom.getAddress(), 5);
                                }
                            }
                        } catch (IOException ioex) {
                            System.out.println(
                                    "??????????");
                        } catch (MessagingException mex) {
                            System.out.println(
                                    "??????????");
                        }
                    }
                }
            });

            // Check mail once in "freq" MILLIseconds
            int freq = 1000; //??
            boolean supportsIdle = false;
            try {
                if (folder instanceof IMAPFolder) {
                    IMAPFolder f = (IMAPFolder) folder;
                    f.idle();
                    supportsIdle = true;
                }
            } catch (FolderClosedException fex) {
                throw fex;
            } catch (MessagingException mex) {
                supportsIdle = false;
            }
            for (;;) {
                if (supportsIdle && folder instanceof IMAPFolder) {
                    IMAPFolder f = (IMAPFolder) folder;
                    f.idle();
                } else {
                    Thread.sleep(freq); // sleep for freq milliseconds

                    // This is to force the IMAP server to send us
                    // EXISTS notifications. 
                    folder.getMessageCount();
                }
            }

        } catch (Exception ex) {
            System.out.println("??????????");
        }
    }
}

From source file:esg.node.components.monitoring.ESGMonitor.java

private void startMonitoring() {
    log.trace("launching system monitor timer");
    long delay = Long.parseLong(props.getProperty("monitor.initialDelay"));
    long period = Long.parseLong(props.getProperty("monitor.period"));
    log.trace("monitoring delay: " + delay + " sec");
    log.trace("monitoring period: " + period + " sec");

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        public final void run() {
            //log.trace("Checking for new node information... [busy? "+ESGMonitor.this.isBusy+"]");
            if (!ESGMonitor.this.isBusy) {
                ESGMonitor.this.isBusy = true;
                if (fetchNodeInfo()) {
                    //TODO
                    monitorDAO.markLastCompletionTime();
                }/* w w  w .  j a va 2  s .  c  o  m*/
                ESGMonitor.this.isBusy = false;
            }
        }
    }, delay * 1000, period * 1000);
}

From source file:org.camunda.bpm.example.spring.servlet.pa.ArquillianTest.java

public void waitForJobExecutorToProcessAllJobs(JobExecutor jobExecutor, long maxMillisToWait) {

    int checkInterval = 1000;

    jobExecutor.start();//w  w  w  .ja v a  2 s .  c  o  m

    try {
        Timer timer = new Timer();
        InteruptTask task = new InteruptTask(Thread.currentThread());
        timer.schedule(task, maxMillisToWait);
        boolean areJobsAvailable = true;
        try {
            while (areJobsAvailable && !task.isTimeLimitExceeded()) {
                Thread.sleep(checkInterval);
                areJobsAvailable = areJobsAvailable();
            }
        } catch (InterruptedException e) {
        } finally {
            timer.cancel();
        }
        if (areJobsAvailable) {
            throw new ProcessEngineException("time limit of " + maxMillisToWait + " was exceeded");
        }

    } finally {
        jobExecutor.shutdown();
    }
}

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

@Override
public String export(Set<String> fields, MaalrQuery query) throws Exception {
    File dir = new File("exports");
    dir.mkdirs();//from   w  ww  .  j a v a2s .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:net.frygo.findmybuddy.GCMIntentService.java

private static void generateAcceptfriendNotification(Context context, String message, String status) {

    Random rand = new Random();
    int x = rand.nextInt();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, customlistview.class);
    if (status.equalsIgnoreCase("accept"))
        message = message + " added you as buddy";
    else//from  ww  w  . ja v  a  2 s  .  c  o  m
        message = message + " rejected you as buddy";
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_CANCEL_CURRENT);

    Notification notification = new Notification(R.drawable.logo, message, System.currentTimeMillis());
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(x, notification);

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock mWakelock = pm
            .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, title);
    mWakelock.acquire();

    // Timer before putting Android Device to sleep mode.
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        public void run() {
            mWakelock.release();
        }
    };
    timer.schedule(task, 5000);

}