问题
I need to execute a method on a specific date of every year, how could I do this in java?
Thanks,
Chris.
回答1:
In order of preference:
The Quartz library (highly recommended).
java.util.Timer
. Not as powerful as Quartz, but good for simple jobs.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.
回答2:
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
回答4:
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.
来源:https://stackoverflow.com/questions/4295187/java-execute-method-on-specific-date