Spring Batch is a powerful framework for managing large volumes of data processing. Once your Spring Batch job is configured to handle tasks like fetching college names and their associated websites, it's essential to have a mechanism to trigger this job. In this article, we'll look at three ways to implement a Job Runner for the CollegeBatchJobConfig
in a Spring Boot application:
- CommandLineRunner to trigger the job on application startup.
- Scheduled Job to run the job at regular intervals.
- REST Endpoint to expose a manual trigger for the job.
1. Using CommandLineRunner to Trigger the Job on Application Startup
The CommandLineRunner interface allows us to execute code as soon as the application starts. This is a great option if you want the job to run automatically whenever the application starts.
Here’s how to implement the job runner using CommandLineRunner
:
java
@Configuration
public class CollegeJobRunnerConfig {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job collegeDataJob;
@Bean
public CommandLineRunner runJob() {
return args -> {
try {
JobParameters jobParameters = new JobParametersBuilder()
.addLong("startAt", System.currentTimeMillis())
.toJobParameters();
JobExecution execution = jobLauncher.run(collegeDataJob, jobParameters);
System.out.println("Job Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
};
}
}
In the code above, the runJob
method is executed when the application starts. It triggers the collegeDataJob
by passing job parameters such as the current time, ensuring the job is uniquely identified for each execution.
2. Scheduling the Job to Run at Regular Intervals
If you prefer the job to run periodically, Spring provides the @Scheduled
annotation for scheduled tasks. This can be configured to trigger the job at fixed intervals, such as hourly, daily, or at a specific cron expression.
Here’s an example of scheduling the job every hour:
java
@Configuration
@EnableScheduling
public class ScheduledCollegeJobRunner {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job collegeDataJob;
@Scheduled(cron = "0 0 * * * ?") // Example: Runs every hour
public void runJob() {
try {
JobParameters jobParameters = new JobParametersBuilder()
.addLong("startAt", System.currentTimeMillis())
.toJobParameters();
JobExecution execution = jobLauncher.run(collegeDataJob, jobParameters);
System.out.println("Job Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
}
}
The @Scheduled
annotation defines the cron expression that controls the frequency of the job execution. In this example, the job runs every hour (0 0 * * * ?
), but you can modify the cron expression as needed.
Make sure to enable scheduling in the configuration with the @EnableScheduling
annotation.
3. Exposing a Job Trigger via REST Endpoint
Another common approach is to expose a REST endpoint that triggers the job manually. This gives you the flexibility to run the job whenever you need through an HTTP request.
Here’s how to expose a job runner via a REST controller:
java
@RestController
@RequestMapping("/jobs")
public class CollegeJobController {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job collegeDataJob;
@GetMapping("/run")
public ResponseEntity<String> runJob() {
try {
JobParameters jobParameters = new JobParametersBuilder()
.addLong("startAt", System.currentTimeMillis())
.toJobParameters();
JobExecution execution = jobLauncher.run(collegeDataJob, jobParameters);
return ResponseEntity.ok("Job Status : " + execution.getStatus());
} catch (Exception e) {
return ResponseEntity.status(500).body("Job failed with error: " + e.getMessage());
}
}
}
In this case, the job is triggered by sending a GET
request to /jobs/run
. When the request is made, the controller triggers the job and returns the job status in the response. If there's an error during execution, it returns a 500 status with the error message.
This approach is especially useful when you need to trigger the job externally, such as through a user interface or an external system.
Summary
- CommandLineRunner: Automatically runs the job when the application starts. This is ideal if you want to initiate the job on startup.
- Scheduled Job: Runs the job at specified intervals using
@Scheduled
. This is perfect for periodic execution, such as daily or hourly jobs. - REST Endpoint: Exposes an endpoint for manual triggering of the job via an HTTP request. This approach provides flexibility for external triggers.
Choose the method that best fits your application's needs. If you want the job to run as soon as the application starts, go with CommandLineRunner. For periodic execution, use the scheduled approach. If you need manual control, expose a REST endpoint.