Monday, July 2, 2012


Scheduling/Scheduler in Spring:


Entry in application-servlet.xml file:

<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
      xmlns:task="http://www.springframework.org/schema/task"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.directwebremoting.org/schema/spring-dwr  http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">



<!-- Configuration for Sceduler. The "task" namespace is used here to declare the scheduler and executor.The third line of the XML asks Spring to scan classes for annotations related to scheduled tasks.If you have multiple tasks to run at the same time, you can get them to run in parallel by increasing the pool size.-->
      <task:scheduler id="taskScheduler"/>
      <task:executor id="taskExecutor" pool-size="1"/>
      <task:annotation-driven executor="taskExecutor" scheduler="taskScheduler"/>



Our Scheduler Class:

@Service
public class Scheduler{
      //@Scheduled(cron = "* * 1 * * ?")
      @Scheduled(fixedRate=60000)
      public void runReport() {
     System.out.println("Generating report/Sending Mail/Performing Check on Db");
      }
}

We can also use cron expression for a definite time:

The pattern is a list of six single space-separated fields: representing second, minute, hour, day, month, weekday. Month and weekday names can be given as the first three letters of the English names.

Example patterns:

  • "0 0 * * * *" = the top of every hour of every day.
  • "*/10 * * * * *" = every ten seconds.
  • "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
  • "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
  • "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
  • "0 0 0 25 12 ?" = every Christmas Day at midnight

field                    allowed values
 -----                     --------------
 minute               0-59
 hour                    0-23
 day of month    1-31
 month                1-12 (or names, see below)
 day of week       0-7 (0 or 7 is Sun, or use names)

and cron expressions can also be read from the properties file :
using ${cron.expression}
in properties file: cron.expression=*/10 * * * * *

http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/scheduling.html

Java based configuration from Spring 3.1.4.RELEASE, we can eliminate xml configuration by using:

@Configuration
@EnableScheduling

No comments:

Post a Comment