Schedule at 24hrs interval

前端 未结 4 1278
萌比男神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();
      
    0 讨论(0)
  • 2021-01-20 02:24

    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.

    0 讨论(0)
  • 2021-01-20 02:28

    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());
    }
    
    0 讨论(0)
  • 2021-01-20 02:35

    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);
    }
    
    0 讨论(0)
提交回复
热议问题