Archive

Posts Tagged ‘cron’

Using @Scheduled annotation in spring

August 12th, 2015 No comments

If you are looking to scheduled task and are using spring framework, there are couple of alternatives

a) Quartz : Spring has support for quartz

b) @Scheduler annotation : Simple and easy.

Here is the code sample


public class SchedulerManager {

 @Scheduled(fixedRate = 10000)
 public void testMyScheduler(){

System.out.println(" I am the scheduler >>>>>>");
}
}

10000 is in milliseconds so you would see output after 10 seconds .

If you want to start after some delay and not at application start up


public class SchedulerManager {

@Scheduled(initialDelay=2000, fixedRate = 10000)
public void testMyScheduler(){

System.out.println(" I am the scheduler >>>>>>");
}
}

The method gets executed after delay of 2 seconds.

And if you want to use cron expression


public class SchedulerManager {

@Scheduled(cron="0 0/1 * * * ?")
public void testMyScheduler(){

System.out.println(" I am the cron scheduler >>>>>>");
}
}

The above method executes after 1 minute.

Remember spring calls it a cron expression but in fact it is not a true cron expression. If you use the actual cron expression , you would see some exception like

Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method ‘testMySchedulerWithQuartz': Cron expression must consist of 6 fields (found 7 in “0 0/1 * * * ? *”)

And here is the simple applicationContext.xml file


 <task:annotation-driven />
 <bean id="scheduleManager" class="com.skg.demo.scheduler.SchedulerManager" />

The output after 10 seconds will be


I am the scheduler >>>>>>

I am the scheduler >>>>>>

I am the scheduler >>>>>>

You do not need any other configuration setup

Spring has complete documentation on various strategies