Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schedule at 24hrs interval

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.

like image 268
Akhil K Nambiar Avatar asked Dec 27 '25 16:12

Akhil K Nambiar


1 Answers

Here are few approach, from simplest to most comprehensive:

  1. 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.

  2. java.util.Timer#scheduleAtFixedRate() - simple, built-in Java solution.

  3. @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() {
      //...
    }
    
  4. 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();
    
like image 199
Tomasz Nurkiewicz Avatar answered Dec 30 '25 06:12

Tomasz Nurkiewicz