Java - Execute method on specific date [closed]

别等时光非礼了梦想. 提交于 2019-12-30 13:44:31

问题


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:

  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.




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!