Search This Blog

Monday 4 February 2013

Scheduling via Spring

Spring provides support for scheduling activities. One way to do it is using java's Timer class. I created a simple program to display random messages.
public class MessageAgent {

    public static final String[] messages = {
        "What the heck !!",
        "This is done",
        "I quit",
        "Great job",
        "This rocks"
    };
    
    public String getMessage() {
        final int max = messages.length;
        return messages[(int) (max*Math.random())];
    }
}
The class returns a random message on every call. The next step is to create a Task that can be executed by the Scheduler.
public class DisplayMsgTask extends TimerTask {

    @Autowired
    private MessageAgent displayMessageAgent;
    private final SimpleDateFormat dtF = new SimpleDateFormat("hh:mm:ss");

    @Override
    public void run() {

        System.out.println(dtF.format(new Date()) + " : "
                + this.displayMessageAgent.getMessage());
    }

}
The next step is to set up a scheduler and schedule the task for execution.
<context:annotation-config/>

<!-- The bean -->
<bean id="displayMessageAgent" class="com.task.MessageAgent" />

<!-- The task -->
<bean id="displayMessageTask" class="com.task.DisplayMsgTask" />

<!-- The schedule -->
<bean id="scheduleDisplayMessageTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
    <property name="timerTask" ref="displayMessageTask"/>
    <property name="period" value="1000"/> <!-- in milliseconds -->
</bean>
    
<!-- The scheduler -->
<bean class="org.springframework.scheduling.timer.TimerFactoryBean">
    <property name="scheduledTimerTasks">
        <list>
            <ref bean="scheduleDisplayMessageTask"/>
        </list>
    </property>
</bean>
As can be seen we created a task and scheduled it to execute every 1 second. The next bean is the timer. It will run all the scheduled tasks.
I created a Client to start the Spring Container (and thereby the Scheduler)
public class Client {
    public static void main(String[] args) throws FileNotFoundException {
        final ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "spring-tasks.xml");
        System.out.println("Starting the context - " + applicationContext);
    }
}
The logs indicate the code execution:
Apr 12, 2012 7:17:41 PM org.springframework.scheduling.timer.TimerFactoryBean afterPropertiesSet
INFO: Initializing Timer
Starting the context - org.springframework.context.support.ClassPathXmlApplicationContext@19c26f5: startup date [Thu Apr 12 19:17:40 IST 2012]; root of context hierarchy
07:17:41 : I quit
07:17:42 : This rocks
07:17:43 : What the heck !!
07:17:44 : I quit
07:17:45 : What the heck !!
07:17:46 : This is done
07:17:47 : I quit
07:17:48 : I quit
07:17:49 : This is done
07:17:50 : Great job
An additional configuration available in the ScheduledTimerTask is the amount of time by which we would like to delay the start of task(for the first run only).
<bean id="scheduleDisplayMessageTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
    <property name="timerTask" ref="displayMessageTask"/>
    <property name="period" value="1000"/> <!-- in milliseconds -->
    <property name="delay" value="5000"/> <!-- in milliseconds -->
</bean>

No comments:

Post a Comment