Reputation: 655
Right now my program accepts an input, and formats it into a Date. But I want it to call a method whenever that date is reached. How could I do this without the use of any libraries like Quartz?
Code I have for the input:
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();
}
Upvotes: 0
Views: 269
Reputation: 339432
The Timer
class mentioned in another Answer is the old way.
As of Java 5, the modern way is the Executors suite of interfaces and classes, specifically the ScheduledExecutorService
.
Be sure to read up, including searching StackOverflow for more info. Specifically, be aware that any uncaught exception bubbling up to your main code running in the Executor will cause service to cease. Any future scheduled runs of your code will be terminated. The solution is simple: Always surround the main code of your executor with a try-catch to catch any Exception
(and maybe even Error
, or, Throwable
).
Timer
In Servlet/JaveEEMost especially, do not use Timer
in a Servlet or Java EE (Enterprise Edition) app. See this Answer by BalusC for details.
Upvotes: 0
Reputation: 1259
You can use Timer and TimerTask object.
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 object allow you to handle multiple TimerTask instance!
Upvotes: 1
Reputation: 880
After the line where you parse the date, add t.schedule(task, date)
, where 't' is a Timer, and 'task' is a TimerTask that represents the method you want to be executed at the given date.
Upvotes: 0