Clicking a button. It's hard to think of a simpler way to stop a job. The next technique, although not
as easy, doesn't require you to deploy anything else for it to work.
Stopping Using CommandLineJobRunner
Earlier in this chapter, you saw that a number of command-line options are available for
CommandLineJobRunner that you haven't explored yet. Two of them are related to stopping and restarting
jobs. This section looks at how to stop and restart jobs with CommandLineJobRunner .
When you execute jobs via CommandLineJobRunner , you build a jar file and execute it via the standard
Java -jar command, as covered earlier. When a job is running, you can stop it gracefully by executing
the command shown in Listing 6-33.
Listing 6-33. Calling CommandLineJobRunner to Stop a Job
java -jar transactionJob.jar jobs/transactionJob.xml 7007 -stop
The command should look similar to all the others you've used. You call the executable jar file
( transactionJob.jar in this case) that has CommandLineJobRunner configured as its main class in META-
INF . CommandLineJobRunner requires two parameters: the path to an XML file that defines a job and either
a job name (as it's been called up to now) or a job execution id. In this case, you're passing it the job
execution id (7007 is the id for this execution, as found in the BATCH_JOB_EXECUTION table or via
Spring Batch Admin) to specify which job execution to stop. If you choose to pass in the job name in this
situation, all running instances of the job are stopped.
After a job is stopped this way, how do you restart it? One of the other options for
CommandLineJobRunner should give you a hint. There is a -restart option that you haven't seen yet. As
you can guess, you can restart execution with the same command you used to stop it, changing only -
stop to -restart , as shown in Listing 6-34.
Listing 6-34. Calling CommandLineJobRunner to Restart a Stopped Job
java -jar transactionJob.jar jobs/transactionJob.xml 7007 -restart
Starting, stopping, and restarting a job from the command line are common occurrences. Up to this
point, this chapter has talked about stopping jobs in a way that occurs by your choice: you choose to
stop the job programmatically, or you choose to stop the job via Spring Batch Admin. However, some
situations are outside of your control. Errors occur. The next section discusses how stopping a job works
when an Exception is thrown.
No job is perfect—not even yours. Errors happen. You may receive bad data. You may forget one null
check that causes a NullPointerException at the worst of times. How you handle errors using Spring
Batch is important. This section discusses the options for what to do when an exception is thrown
during your batch job and how to implement them.
Stopping the Job
It should come as little surprise that the default behavior of Spring Batch is probably the safest: stopping
the job and rolling back the current chunk. This is one of the driving concepts of chunk-based