or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

auto-configuration.mdconfiguration-properties.mdcustomization.mdindex.mdjob-execution.md

job-execution.mddocs/

0

# Job Execution Management

1

2

Spring Boot Batch Starter provides automatic job execution capabilities with application startup integration, exit code generation, and comprehensive job lifecycle management.

3

4

## Capabilities

5

6

### JobLauncherApplicationRunner

7

8

Automatically executes batch jobs on application startup with configurable job selection and parameter passing.

9

10

```java { .api }

11

/**

12

* ApplicationRunner that automatically launches batch jobs on application startup.

13

* Supports job selection, parameter conversion, and integration with Spring Boot lifecycle.

14

*/

15

public class JobLauncherApplicationRunner implements ApplicationRunner, InitializingBean {

16

17

/**

18

* Default execution order for the job launcher runner

19

*/

20

public static final int DEFAULT_ORDER = 0;

21

22

/**

23

* Constructor for automatic job execution with default configuration

24

*/

25

public JobLauncherApplicationRunner(

26

JobLauncher jobLauncher,

27

JobExplorer jobExplorer,

28

JobRepository jobRepository);

29

30

/**

31

* Executes configured batch jobs with command-line arguments as job parameters

32

* @param args Application arguments that can be converted to job parameters

33

* @throws Exception if job execution fails

34

*/

35

public void run(ApplicationArguments args) throws Exception;

36

37

/**

38

* Executes configured batch jobs with string arguments

39

* @param args String arguments that can be converted to job parameters

40

* @throws JobExecutionException if job execution fails

41

*/

42

public void run(String... args) throws JobExecutionException;

43

44

/**

45

* Sets the specific job name to execute on startup

46

* @param jobName Name of the job to execute (must match a bean name)

47

*/

48

public void setJobName(String jobName);

49

50

/**

51

* Sets custom job parameters converter for argument processing

52

* @param converter Custom converter for transforming arguments to job parameters

53

*/

54

public void setJobParametersConverter(JobParametersConverter converter);

55

56

/**

57

* Sets the execution order relative to other ApplicationRunners

58

* @param order Execution order (lower values execute first)

59

*/

60

public void setOrder(int order);

61

62

/**

63

* Gets the execution order of this runner

64

* @return Current execution order

65

*/

66

public int getOrder();

67

68

/**

69

* Sets the job registry for looking up registered jobs

70

* @param jobRegistry Registry containing job definitions

71

*/

72

public void setJobRegistry(JobRegistry jobRegistry);

73

74

/**

75

* Sets the collection of job beans available for execution

76

* @param jobs Collection of job beans

77

*/

78

public void setJobs(Collection<Job> jobs);

79

80

/**

81

* Sets the application event publisher for publishing job execution events

82

* @param publisher Event publisher for job events

83

*/

84

public void setApplicationEventPublisher(ApplicationEventPublisher publisher);

85

86

/**

87

* Validates the runner configuration after properties are set

88

* @throws IllegalStateException if configuration is invalid

89

*/

90

public void afterPropertiesSet() throws IllegalStateException;

91

92

/**

93

* @deprecated since 3.0.10 for removal, use afterPropertiesSet() instead

94

*/

95

@Deprecated(since = "3.0.10", forRemoval = true)

96

public void validate();

97

98

/**

99

* Executes a specific job with given parameters

100

* @param job The job to execute

101

* @param jobParameters Parameters for job execution

102

* @throws JobExecutionAlreadyRunningException if job is already running

103

* @throws JobRestartException if job restart fails

104

* @throws JobInstanceAlreadyCompleteException if job instance is already complete

105

* @throws JobParametersInvalidException if job parameters are invalid

106

*/

107

protected void execute(Job job, JobParameters jobParameters)

108

throws JobExecutionAlreadyRunningException, JobRestartException,

109

JobInstanceAlreadyCompleteException, JobParametersInvalidException;

110

111

/**

112

* Launches jobs based on properties configuration

113

* @param properties Properties containing job configuration

114

* @throws JobExecutionException if job execution fails

115

*/

116

protected void launchJobFromProperties(Properties properties) throws JobExecutionException;

117

}

118

```

119

120

**Usage Examples:**

121

122

```java

123

@SpringBootApplication

124

public class BatchApplication {

125

126

@Bean

127

public Job dailyReportJob(JobRepository jobRepository, Step reportStep) {

128

return new JobBuilder("dailyReportJob", jobRepository)

129

.start(reportStep)

130

.build();

131

}

132

133

// Job runs automatically on startup with default configuration

134

public static void main(String[] args) {

135

SpringApplication.run(BatchApplication.class, args);

136

}

137

}

138

139

// Run with custom job parameters

140

java -jar myapp.jar --inputFile=data.csv --outputDir=results/

141

```

142

143

### Custom Job Runner Configuration

144

145

Customize job execution behavior through bean configuration:

146

147

```java

148

@Configuration

149

public class BatchJobConfiguration {

150

151

@Bean

152

public JobLauncherApplicationRunner customJobRunner(

153

JobLauncher jobLauncher,

154

JobExplorer jobExplorer,

155

JobRepository jobRepository) {

156

157

JobLauncherApplicationRunner runner = new JobLauncherApplicationRunner(

158

jobLauncher, jobExplorer, jobRepository);

159

160

// Configure specific job to run

161

runner.setJobName("mySpecificJob");

162

163

// Set custom job parameters

164

JobParameters params = new JobParametersBuilder()

165

.addString("environment", "production")

166

.addLong("timestamp", System.currentTimeMillis())

167

.toJobParameters();

168

runner.setJobParameters(params);

169

170

// Set execution order

171

runner.setOrder(1);

172

173

return runner;

174

}

175

}

176

```

177

178

### JobExecutionExitCodeGenerator

179

180

Generates application exit codes based on batch job execution results, enabling proper integration with external job schedulers and monitoring systems.

181

182

```java { .api }

183

/**

184

* Generates application exit codes based on job execution results.

185

* Implements both ApplicationListener for job events and ExitCodeGenerator for Spring Boot.

186

*/

187

public class JobExecutionExitCodeGenerator

188

implements ApplicationListener<JobExecutionEvent>, ExitCodeGenerator {

189

190

/**

191

* Handles job execution events to track job results

192

* @param event Job execution event containing execution details

193

*/

194

public void onApplicationEvent(JobExecutionEvent event);

195

196

/**

197

* Generates exit code based on accumulated job execution results

198

* @return Exit code (0 for success, positive integers for various failure types)

199

*/

200

public int getExitCode();

201

}

202

```

203

204

**Exit Code Mapping:**

205

206

```java

207

// Exit codes correspond to BatchStatus ordinal values:

208

// 0 = COMPLETED (success)

209

// 1 = STARTING

210

// 2 = STARTED

211

// 3 = STOPPING

212

// 4 = STOPPED

213

// 5 = FAILED

214

// 6 = ABANDONED

215

// 7 = UNKNOWN

216

```

217

218

**Usage Examples:**

219

220

```java

221

@SpringBootApplication

222

public class BatchApplication {

223

224

public static void main(String[] args) {

225

System.exit(SpringApplication.exit(

226

SpringApplication.run(BatchApplication.class, args)));

227

}

228

229

@Bean

230

public Job riskyJob(JobRepository jobRepository, Step riskyStep) {

231

return new JobBuilder("riskyJob", jobRepository)

232

.start(riskyStep)

233

.build();

234

}

235

}

236

237

// Shell script can check exit codes

238

#!/bin/bash

239

java -jar batch-app.jar

240

EXIT_CODE=$?

241

if [ $EXIT_CODE -eq 0 ]; then

242

echo "Batch job completed successfully"

243

elif [ $EXIT_CODE -eq 5 ]; then

244

echo "Batch job failed"

245

exit 1

246

fi

247

```

248

249

### JobExecutionEvent

250

251

Spring application event that encapsulates job execution information for event-driven batch processing.

252

253

```java { .api }

254

/**

255

* Spring ApplicationEvent that wraps JobExecution for event-driven processing

256

*/

257

public class JobExecutionEvent extends ApplicationEvent {

258

259

/**

260

* Creates a new job execution event

261

* @param execution The job execution that triggered this event

262

*/

263

public JobExecutionEvent(JobExecution execution);

264

265

/**

266

* Returns the job execution associated with this event

267

* @return JobExecution containing execution details, status, and metadata

268

*/

269

public JobExecution getJobExecution();

270

}

271

```

272

273

**Usage Examples:**

274

275

```java

276

@Component

277

public class BatchJobEventListener {

278

279

@EventListener

280

public void handleJobExecution(JobExecutionEvent event) {

281

JobExecution jobExecution = event.getJobExecution();

282

283

System.out.println("Job: " + jobExecution.getJobInstance().getJobName());

284

System.out.println("Status: " + jobExecution.getStatus());

285

System.out.println("Start Time: " + jobExecution.getStartTime());

286

System.out.println("End Time: " + jobExecution.getEndTime());

287

288

if (jobExecution.getStatus() == BatchStatus.FAILED) {

289

// Handle job failure - send alerts, log errors, etc.

290

handleJobFailure(jobExecution);

291

}

292

}

293

294

private void handleJobFailure(JobExecution jobExecution) {

295

// Custom failure handling logic

296

List<Throwable> failureExceptions = jobExecution.getFailureExceptions();

297

for (Throwable exception : failureExceptions) {

298

System.err.println("Job failed with: " + exception.getMessage());

299

}

300

}

301

}

302

```

303

304

### Job Parameter Conversion

305

306

Automatic conversion of command-line arguments to job parameters with customization options.

307

308

```java { .api }

309

/**

310

* Interface for converting application arguments to job parameters

311

*/

312

public interface JobParametersConverter {

313

314

/**

315

* Converts properties to JobParameters

316

* @param properties Input properties (typically from command line)

317

* @return JobParameters for job execution

318

*/

319

JobParameters getJobParameters(Properties properties);

320

321

/**

322

* Converts JobParameters back to properties

323

* @param params JobParameters to convert

324

* @return Properties representation

325

*/

326

Properties getProperties(JobParameters params);

327

}

328

```

329

330

**Custom Parameter Converter:**

331

332

```java

333

@Component

334

public class CustomJobParametersConverter implements JobParametersConverter {

335

336

@Override

337

public JobParameters getJobParameters(Properties properties) {

338

JobParametersBuilder builder = new JobParametersBuilder();

339

340

// Convert string properties to typed parameters

341

for (String key : properties.stringPropertyNames()) {

342

String value = properties.getProperty(key);

343

344

if (key.endsWith(".date")) {

345

try {

346

Date date = DateFormat.getDateInstance().parse(value);

347

builder.addDate(key.replace(".date", ""), date);

348

} catch (ParseException e) {

349

builder.addString(key, value);

350

}

351

} else if (key.endsWith(".long")) {

352

try {

353

long longValue = Long.parseLong(value);

354

builder.addLong(key.replace(".long", ""), longValue);

355

} catch (NumberFormatException e) {

356

builder.addString(key, value);

357

}

358

} else {

359

builder.addString(key, value);

360

}

361

}

362

363

// Add timestamp for uniqueness

364

builder.addLong("run.timestamp", System.currentTimeMillis());

365

366

return builder.toJobParameters();

367

}

368

369

@Override

370

public Properties getProperties(JobParameters params) {

371

Properties properties = new Properties();

372

373

for (Map.Entry<String, JobParameter<?>> entry : params.getParameters().entrySet()) {

374

properties.setProperty(entry.getKey(), entry.getValue().toString());

375

}

376

377

return properties;

378

}

379

}

380

```

381

382

## Job Selection Strategies

383

384

### Single Job Applications

385

386

When only one job bean exists, it runs automatically:

387

388

```java

389

@SpringBootApplication

390

public class SingleJobApplication {

391

392

@Bean

393

public Job onlyJob(JobRepository jobRepository, Step step) {

394

return new JobBuilder("onlyJob", jobRepository)

395

.start(step)

396

.build();

397

}

398

// Runs automatically on startup

399

}

400

```

401

402

### Multiple Job Applications

403

404

When multiple jobs exist, specify which one to run:

405

406

```properties

407

# Required when multiple jobs are present

408

spring.batch.job.name=specificJobName

409

```

410

411

```java

412

@SpringBootApplication

413

public class MultiJobApplication {

414

415

@Bean

416

public Job job1(JobRepository jobRepository, Step step1) {

417

return new JobBuilder("job1", jobRepository).start(step1).build();

418

}

419

420

@Bean

421

public Job job2(JobRepository jobRepository, Step step2) {

422

return new JobBuilder("job2", jobRepository).start(step2).build();

423

}

424

425

// Without spring.batch.job.name property, application will fail to start

426

}

427

```

428

429

### Conditional Job Execution

430

431

Disable automatic execution and control jobs programmatically:

432

433

```properties

434

spring.batch.job.enabled=false

435

```

436

437

```java

438

@Component

439

public class ManualJobLauncher {

440

441

@Autowired

442

private JobLauncher jobLauncher;

443

444

@Autowired

445

private Job myJob;

446

447

public void runJobManually() throws Exception {

448

JobParameters params = new JobParametersBuilder()

449

.addLong("startedAt", System.currentTimeMillis())

450

.toJobParameters();

451

452

JobExecution execution = jobLauncher.run(myJob, params);

453

System.out.println("Job Status: " + execution.getStatus());

454

}

455

}

456

```