用于系统动态日期和发出警报的Java代码



我正试图编写一个java代码,在一天中的特定时间发出警报,但我不知道为什么我会失败(请对我的问题保持温和,因为我对编程完全陌生)。我有这个代码

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

我应该尝试刷新页面吗?请帮忙。。。

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

同样使用schedule意味着执行器线程只运行一次。使用scheduleAtFixedRate

此外,您还需要在EDT中调用showMessageDialog,以确保该调用不会阻塞Executor Thread

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);

如果你想每30秒调用ExecutorService,而不是重复检查当前秒,你可以调用

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

最新更新