Saturday 6 July 2013

Spring Task Execution And Scheduling

If your applications needs a single or batch of tasks to be executed in an asynchronous manner at some point in future, then what you are ultimately looking for is TaskExecuter implementations and TaskScheduler of spring framework.
TaskExecuter allows us to execute tasks in an asynchronous manner
TaskScheduler allows us to schedule a task to run at some point in future.
To know more about taskexecuter and taskscheduler visit http://static.springsource.org/spring/docs/3.0.x/reference/scheduling.html

Here we can see how to declare taskexecuter and taskscheduler in spring configuration file
and how to create a bean with cron job @Scheduled annotation to schedule the date and time of execution.

Spring configuration file

Now to schedule a job for every 20 minutes

Make sure to replace xxxxxxxxxxx of <context:component-scan base-package="xxxxxxxxxxx" /> with the package name of your ScheduleService class.

Now, lets analyse the attributes of task executer and scheduler.


<task:scheduler id="taskScheduler" pool-size="1"/>

pool-size="1": Here the value "1" indicates that only one task can be scheduled at a time. If you want one or more task to be scheduled in an asynchronous manner, increase its value. For example, to schedule 5 tasks at a time ( <task:scheduler id="taskScheduler" pool-size="5"/> )

<task:executor id="taskExecutor" pool-size="1" queue-capacity="2"/>

As in the case of scheduler, pool-size with value "1" indicates that only one task can be executed at a time. If you set value 1 to pool-size of scheduler and executer, it behaves in a synchronous manner.ie, only one task can be scheduled and only one task can be executed at a time. If you want to execute more tasks at a time, just increase the value of the pool-size. For example, If you want to execute 5 tasks at a time  
<task:executor id="taskExecutor" pool-size="5" queue-capacity="2"/>

<task:executor id="taskExecutor" pool-size="1" queue-capacity="2"/>

Capacity of TaskExecuter queue. Before an item is pushed to the pool, it checks the current capacity of the pool. If the pool is completely filled and busy, it will be pushed to the queue, and it remains there until the TaskExecuter finish running a task. Here the value "2" defines that only 2 tasks can be put in to the queue before it moves on to the pool.


1 comment:

  1. Very clean and simple explanation. I tried the docs and stackoverflow but this is where I could get a basic understanding of the difference between scheduler and executor.

    ReplyDelete