Schedule at 24hrs interval

前端 未结 4 1277
萌比男神i
萌比男神i 2021-01-20 02:00

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

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-20 02:24

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

提交回复
热议问题