0

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();
                }
Arman
  • 615
  • 2
  • 6
  • 20

3 Answers3

1

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!

antoniodvr
  • 1,251
  • 1
  • 14
  • 15
0

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.

Martin M J
  • 770
  • 1
  • 4
  • 12
0

The Timer class mentioned in another Answer is the old way.

Executor

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

Never Use Timer In Servlet/JaveEE

Most especially, do not use Timer in a Servlet or Java EE (Enterprise Edition) app. See this Answer by BalusC for details.

Community
  • 1
  • 1
Basil Bourque
  • 218,480
  • 72
  • 657
  • 915