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 appl
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();