现在我的程序接受输入,并将其格式化为日期。但我希望它在达到该日期时调用方法。如果不使用像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();
}
答案 0 :(得分:1)
您可以使用Timer和TimerTask对象。
Flux
Timer对象允许您处理多个TimerTask实例!
答案 1 :(得分:0)
答案 2 :(得分:0)
another Answer中提到的Timer
类是旧方法。
从Java 5开始,现代方式是Executors接口和类套件,特别是ScheduledExecutorService
。
请务必阅读,包括搜索StackOverflow以获取更多信息。具体来说,请注意任何未捕获的异常冒泡到Executor中运行的主代码将导致服务停止。您的代码的任何未来计划运行都将终止。解决方案很简单:始终用try-catch包围执行程序的主代码以捕获任何Exception
(甚至可能Error
,或Throwable
)。
Timer
尤其是,不在Servlet或Java EE(企业版)应用中使用Timer
。有关详情,请参阅this Answer BalusC。