Akhil K Nambiar
Akhil K Nambiar

Reputation: 3975

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.

Upvotes: 3

Views: 3386

Answers (4)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340693

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 or @Schedule in - more complex but also more powerful, e.g. accepts expressions:

    @Scheduled(fixedRate=DateUtils.MILLIS_PER_DAY)
    public void generateReport() {
      //...
    }
    
  4. - full blown Java scheduler with clustering and fail-over, misfire handling, full support, etc. Very comprehensive:

    newTrigger().
      withSchedule(
        simpleSchedule().
          withIntervalInHours(24).
          repeatForever()
        ).build();
    

    or

    newTrigger().
      withSchedule(
        cronSchedule().
          dailyAtHourAndMinute(17, 30).  //17:30
        ).build();
    

Upvotes: 6

darijan
darijan

Reputation: 9775

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

Upvotes: 0

steelshark
steelshark

Reputation: 644

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.

Upvotes: 0

Matthias Bruns
Matthias Bruns

Reputation: 900

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

Upvotes: 0

Related Questions