问题
I want to know the best method to schedule a code. I have a code that generates reports and sends mail to a set of people at interval of 24hrs. Its a console based java application. I want to know the best method to schedule that. Sometimes I may need to change that to 12hrs interval. However the application doesn't perform any other task in between the interval.
回答1:
Here are few approach, from simplest to most comprehensive:
sleep()
:TimeUnit.HOURS.sleep(24)
This approach is very simple, do the work and sleep for 24 hours. Actually it is a bit more complex because the report generation takes some time, so you have to sleep slightly shorter. All solutions below handle this transparently.
java.util.Timer#scheduleAtFixedRate() - simple, built-in Java solution.
@Scheduled
annotation in spring or@Schedule
in ejb - more complex but also more powerful, e.g. accepts cron expressions:@Scheduled(fixedRate=DateUtils.MILLIS_PER_DAY) public void generateReport() { //... }
quartz-scheduler - full blown Java scheduler with clustering and fail-over, misfire handling, full cron support, etc. Very comprehensive:
newTrigger(). withSchedule( simpleSchedule(). withIntervalInHours(24). repeatForever() ).build();
or
newTrigger(). withSchedule( cronSchedule(). dailyAtHourAndMinute(17, 30). //17:30 ).build();
回答2:
I am using two ways:
First for non managed code like client code: Chron4J
Second is implmented in the JavaEE framewoks. You can use it via annotating methods when you use an container like Glassfish/JBoss. Would be something like this:
@Schedule(second="*/1", minute="*",hour="*", persistent=false)
public void doWork(){
System.out.println("timer: " + helloService.sayHello());
}
回答3:
I would take a look at the quartz scheduler if I were you. I used in a number of applications and it's really easy to use. You can find more information here: http://quartz-scheduler.org/
If you use the spring stack I would surely recommend it, since it is super easy to configure in xml and let spring inject all the stuff for you.
回答4:
Well, if the program can be idle try something like this
try
{
for (;;) {
//code
Thread.sleep(1000 * 60 * 60 * 24);
//code
}
}
catch(Exception e)
{
System.out.println(e);
}
来源:https://stackoverflow.com/questions/9618027/schedule-at-24hrs-interval