2013-02-09 36 views
0

我想写一个java代码,将在一天中的特定时间发出警报,但我不知道为什么我失败(请温和我的问题,因为我对编程完全陌生)。我有此代码Java代码系统日期动态并给出警报

new ScheduledThreadPoolExecutor(1).schedule(new Runnable() { 
    public void run() { 
     if(Calendar.SECOND==30) 
     { 
      JOptionPane.showMessageDialog(null, "Hola Amigo"); 
     } 
    } 
}, 1, TimeUnit.SECONDS); 

我应该尝试刷新页面吗?请帮助...

回答

2

您正在检查固定常数值Calendar.SECOND13)等于30。显然,这永远不会是真的,所以对话将永远不会出现。您需要在Calendar实例中检查此字段。

也使用schedule意味着执行程序线程只运行一次。使用scheduleAtFixedRate

此外,您需要拨打EDT中的showMessageDialog以确保该呼叫不会阻止ExecutorThread

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); 
scheduler.scheduleAtFixedRate(new Runnable() { 
    public void run() { 
     Calendar calendar = Calendar.getInstance(); 
     int second = calendar.get(Calendar.SECOND); 
     if (second == 30) { 
      SwingUtilities.invokeLater(new Runnable() { 
       @Override 
       public void run() { 
        JOptionPane.showMessageDialog(null, "Hola Amigo"); 
       } 
      }); 
     } 
    } 
}, 1, 1, TimeUnit.SECONDS); 

如果你要拨打的ExecutorService每隔30秒,而不是屡检查当前第二,你可以调用

scheduler.scheduleAtFixedRate(myRunnable, 1, 30, TimeUnit.SECONDS); 
+0

感谢....这实际上不利于问题的解决。 – Bhaskar 2013-02-10 09:26:50