Programming & Development / April 19, 2025

Spring Batch Tasklet-Only Job with Dynamic Status Update via Job Parameters

Spring Batch Tasklet job parameters update database Tasklet-only job Spring Boot batch job status update job runner database interaction

In Spring Batch, a Tasklet is a simple, reusable component that performs a single unit of work. While Spring Batch commonly uses readers, processors, and writers, some use cases only require a Tasklet — such as triggering a process, updating a database, or performing file cleanup.

In this guide, you'll learn how to:

  • Create a Tasklet-only batch job
  • Pass a status value from the job runner
  • Use that status value to update a database

2. Use Case

You want to run a batch job that:

✅ Uses only a Tasklet

✅ Receives a status from the job runner

✅ Updates the status in the database

3. Step-by-Step Implementation

✅ 1. Create a Service to Update the Database

java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StatusUpdateService {

    @Autowired
    private StatusRepository statusRepository;

    public void updateStatus(Long jobExecutionId, String status) {
        StatusEntity entity = statusRepository.findByJobExecutionId(jobExecutionId);
        if (entity != null) {
            entity.setStatus(status);
            statusRepository.save(entity);
        }
    }
}

✅ 2. Implement the Tasklet

java

import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyTasklet implements Tasklet {

    @Autowired
    private StatusUpdateService statusUpdateService;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        String status = chunkContext.getStepContext().getJobParameters().get("status").toString();
        Long jobExecutionId = chunkContext.getStepContext().getStepExecution().getJobExecution().getId();

        System.out.println("Tasklet executing with status: " + status);

        // Update database
        statusUpdateService.updateStatus(jobExecutionId, status);

        return RepeatStatus.FINISHED;
    }
}

✅ 3. Configure the Job and Step

java

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableBatchProcessing
public class BatchConfig {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private MyTasklet myTasklet;

    @Bean
    public Step myTaskletStep() {
        return stepBuilderFactory.get("myTaskletStep")
                .tasklet(myTasklet)
                .build();
    }

    @Bean
    public Job myJob() {
        return jobBuilderFactory.get("myJob")
                .start(myTaskletStep())
                .build();
    }
}

✅ 4. Run the Job from the Application

java

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BatchApplication implements CommandLineRunner {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job myJob;

    public static void main(String[] args) {
        SpringApplication.run(BatchApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        // Dynamically pass "status" to the Tasklet
        JobParameters jobParameters = new JobParametersBuilder()
                .addString("status", "STARTED")
                .toJobParameters();

        JobExecution execution = jobLauncher.run(myJob, jobParameters);
        System.out.println("Job Execution Status: " + execution.getStatus());
    }
}

4. Summary

✅ You created a Tasklet-only Spring Batch job

✅ Passed a status parameter from the job runner

✅ Used the parameter inside the Tasklet to update a database

This approach is great for lightweight background tasks that don't require complex read-process-write logic. It also allows full flexibility via job parameters.

5. Bonus Tips

  • 📌 Make sure your status parameter is serializable if you're using remote job execution or restarts.
  • 🛡️ Always validate parameters inside the Tasklet to avoid null pointer exceptions.
  • 🧪 You can test the Tasklet standalone using Spring’s @SpringBatchTest utilities.



Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex