计时器不更新方法不能正常工作

时间:2013-04-04 10:07:17

标签: java timer

我想将data()方法更新到每个500毫秒,但我的下面的计时器更新数据()方法超过4或5秒。谢谢你..

class RemindTask extends TimerTask {
    public void run() {
            try {

                data();

            } catch (UnsupportedCommOperationException ex) {
                Logger.getLogger(test2.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(test2.class.getName()).log(Level.SEVERE, null, ex);
            } catch (TooManyListenersException ex) {
                Logger.getLogger(test2.class.getName()).log(Level.SEVERE, null, ex);
            }

    }

和计时器触发方法是..

 private void okActionPerformed(java.awt.event.ActionEvent evt) {                                   

if(evt.getSource()==ok)
{
    bul=true;
    if(new communication().bul1==false)
    {
    JOptionPane.showMessageDialog(test2,"GPS CONNECTE");

    }
    //System.out.print(bd.get);
   timer = new Timer();
    timer.schedule(new RemindTask(), 500); 

}

1 个答案:

答案 0 :(得分:1)

您使用的是schedule方法的错误版本。第二个参数是延迟,而不是间隔。您可以参考JavaDoc了解详情。

ScheduledExecutorService优于Timer,下面是代码示例:

ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
ses.scheduleAtFixedRate(new RemindTask(), 0, 500, TimeUnit.MILLISECONDS);

您的RemindTask应该实现Runnable界面:

class RemindTask implements Runnable {
  public void run() {
  // ...
  }
}

另请阅读JavaDoc