Java Reference
In-Depth Information
Because the
JobLauncher
interface doesn't guarantee whether a job is run synchronously or
asynchronously,
SimpleJobLauncher
(the only
JobLauncher
implementation provided by Spring Batch)
leaves it up to the developer by running the job in Spring's
TaskExecutor
. By default,
SimpleJobLauncher
uses Spring's
SyncTaskExecutor
, which executes the job in the current thread. Although this is ok in
many instances, this option is a limiting factor for the number of jobs you run within a single JVM.
Let's look at how
SimpleJobLauncher
is configured. Listing 6-1 shows its configuration with the
optional
taskExecutor
property set. This property allows you, as said previously, to specify the algorithm
used for launching jobs. In this case, you're using Spring's
SimpleAsyncTaskExecutor
to launch the job in
a new thread. However, you can easily configure this to use
ThreadPoolTaskExecutor
to control the
number of threads available
Listing 6-1.
SimpleJobLauncher
Configured with a Task Executor
<bean id="taskExecutor"
class="org.springframework.core.task.SimpleAsyncTaskExecutor"/>
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
<property name="taskExecutor" ref="taskExecutor"/>
</bean>
Although the JobLauncher kicks off the job and defines how it's run (synchronously,
asynchronously, in a thread pool, and so on), it's the job runner that you interact with when you want to
launch a job (as you did in the last chapter's JMX job runner). Next you look at the two job runners that
Spring Batch provides out of the box:
CommandLineJobRunner
and
JobRegistryBackgroundJobRunner
.
Spring Batch Job Runners
When you look at the Spring Batch API, although theoretically there are many ways to run a job (launch
it via a servlet, the command line, JMX, and so on), the framework provides only the two runners
org.springframework.batch.core.launch.support.CommandLineJobRunner
and
org.springframework.batch.core.launch.support.JobRegistryBackgroundJobRunner
. All other options—
servlet, JMX, and so forth—must be custom developed. Let's look at how
CommandLineJobRunner
and
JobRegistryBackgroundJobRunner
are used and why, starting with
CommandLineJobRunner
.
CommandLineJobRunner
CommandLineJobRunner
is the runner you've been using up to now. It serves as an interface for your batch
processes via the command line. It's useful for calling jobs from either a terminal or, more commonly,
shell scripts. It provides four features:
•
Loads the appropriate
ApplicationContext
based on the passed parameter
Parses command-line arguments into a
JobParameters
object
•
•
Locates the job requested based on the parameters passed
•
Uses the configured JobLauncher to execute the requested job