Java执行方法使用Date对象

时间:2015-04-26 18:02:21

标签: java date timer

现在我的程序接受输入,并将其格式化为日期。但我希望它在达到该日期时调用方法。如果不使用像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();
                }

3 个答案:

答案 0 :(得分:1)

您可以使用Timer和TimerTask对象。

Flux

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

答案 1 :(得分:0)

在您解析日期的行之后,添加t.schedule(task, date),其中't'是Timer,'task'是TimerTask,代表您想要的方法在给定日期执行。

答案 2 :(得分:0)

another Answer中提到的Timer类是旧方法。

执行人

从Java 5开始,现代方式是Executors接口和类套件,特别是ScheduledExecutorService

请务必阅读,包括搜索StackOverflow以获取更多信息。具体来说,请注意任何未捕获的异常冒泡到Executor中运行的主代码将导致服务停止。您的代码的任何未来计划运行都将终止。解决方案很简单:始终用try-catch包围执行程序的主代码以捕获任何Exception(甚至可能Error,或Throwable)。

永远不要在Servlet / JaveEE中使用Timer

尤其是,在Servlet或Java EE(企业版)应用中使用Timer。有关详情,请参阅this Answer BalusC