Java 使用日期对象执行方法

Java execute method using a Date object

现在我的程序接受输入,并将其格式化为日期。但我希望它在到达该日期时调用一个方法。如果不使用任何像 Quartz 这样的库,我怎么能做到这一点?

我的输入代码:

                Date date = new Date();
                String inputDate;
                month = (String) comboBoxMonth.getSelectedItem();
                day = Integer.parseInt((String) comboBoxDay.getSelectedItem());
                hours = Integer.parseInt((String) comboBoxTimeH.getSelectedItem());
                minutes = Integer.parseInt((String) comboBoxTimeM.getSelectedItem());

                try {
                    //Month/Day/Year Hour:minute:second
                    inputDate = month + "/" + day + "/" + year + " " + hours + ":" + minutes;
                    date = formatter.parse(inputDate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

在您解析日期的行之后,添加 t.schedule(task, date),其中 't' 是一个 Timer, and 'task' is a TimerTask,表示您希望在给定日期执行的方法。

您可以使用 Timer 和 TimerTask 对象。

Timer timer = new Timer ();
TimerTask myTask = new TimerTask () {
    @Override
    public void run () {
        // call your method here
    }
};

// Schedule the task. Start it when your date is reached!
timer.schedule(myTask, yourDate);

Timer 对象允许您处理多个 TimerTask 实例!

中提到的Timerclass是老办法。

执行者

从 Java 5 开始,现代方式是 Executors suite of interfaces and classes, specifically the ScheduledExecutorService

一定要仔细阅读,包括搜索 Whosebug 以获取更多信息。具体来说,请注意任何未捕获的异常冒泡到执行程序中的主代码 运行 都会导致服务停止。您的代码的任何未来计划运行都将终止。解决方案很简单:始终用 try-catch 包围执行程序的主要代码以捕获任何 Exception (and maybe even Error, or, Throwable).

永远不要在 Servlet/JaveEE

中使用 Timer

最重要的是,不要在 Servlet 或 JavaEE(企业版)应用程序中使用 Timer。有关详细信息,请参阅 this Answer by BalusC