-1

I need to execute a method on a specific date of every year, how could I do this in java?

Thanks,

Chris.

Chris
  • 7
  • 1
  • 2

4 Answers4

4

In order of preference:

  1. The Quartz library (highly recommended).

  2. java.util.Timer. Not as powerful as Quartz, but good for simple jobs.

  3. The EJB timer service. It's poorly documented, it requires a full Java EE container, and it doesn't really do anything that Quartz doesn't.

Mike Baranczak
  • 8,291
  • 8
  • 47
  • 71
3

Check out the Timer Class

The method:

scheduleAtFixedRate(TimerTask task, Date firstTime, long period) 
          Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.

will allow you to do what you want. Just be sure you are using the correct date.

Looking at the API, you will need to define a TimerTask that overloads the run() method. The run() method will contain the method you want to call.

3

If you need something more robust, you can also use Quartz for Cron like scheduling

Victor Grazi
  • 15,563
  • 14
  • 61
  • 94
-3

This will get the current date and time.

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

private String getDateTime() {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    return dateFormat.format(date);
}

Then make a loop that checks the function every second and use an if statement to execute the code you want if the time is the time you want.

Paul
  • 5