skip to content

Tasklet Steps

A tasklet step performs a single action — a cleanup, a stored procedure, a shell command — and reports whether it is finished or should be repeated. Interviewers ask when a tasklet beats a chunk step, and 'when there is no item stream' is the answer.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

explore

questions

5

What is a Tasklet step in Spring Batch, and when would you use one instead of the chunk model?

level: juniorimportance: must knowfreq 70%

answer

  1. One method: execute(StepContribution, ChunkContext)
  2. Returns RepeatStatus FINISHED/CONTINUABLE
  3. Single action: cleanup, stored proc, file move
  4. StepBuilder.tasklet(tasklet, txManager)
  5. Functional interface -> lambda

basics

~10 s

A Tasklet step runs a single custom action once, like a cleanup or a stored procedure call. You implement the Tasklet interface's execute() method. It's for tasks that aren't read-process-write loops over items.

solid answer

~40 s

A Tasklet is the simplest step type in Spring Batch: a functional interface with one method, execute(StepContribution, ChunkContext), that returns a RepeatStatus. You use it for single, self-contained actions — deleting temp files, running a stored procedure, sending a notification, moving files — anything that isn't naturally a read-process-write loop over a collection of items. You build it via StepBuilder.tasklet(theTasklet, transactionManager). Spring wraps the execute() call in a transaction and re-invokes it until you return RepeatStatus.FINISHED. This contrasts with the chunk-oriented model (owned by a sibling topic), which is designed for item-by-item ETL with reader/processor/writer and commit intervals. Reach for a Tasklet when the work is one atomic operation, not iteration over many records.

code

java · 9 lines
java
@Bean
Step deleteTempFilesStep(JobRepository repo, PlatformTransactionManager tx) {
    return new StepBuilder("deleteTempFiles", repo)
        .tasklet((contribution, chunkContext) -> {
            Files.deleteIfExists(Path.of("/tmp/staging.csv"));
            return RepeatStatus.FINISHED;
        }, tx)
        .build();
}

go deeper

for a junior

Should know a Tasklet runs a single custom action via execute() and returns RepeatStatus.

for a middle

Should wire it with StepBuilder.tasklet(tasklet, txManager) and know both args of execute().

for a senior

Should articulate transaction wrapping, restart implications, and Tasklet-vs-chunk selection criteria.

for a principal

Should reason about transaction duration, idempotency/restartability, and when to decompose long work via CONTINUABLE or ExecutionContext state.

## What a Tasklet is A **step** in Spring Batch is one phase of a **job** (a batch process). Spring Batch offers two ways to build a step's business logic: 1. **Chunk-oriented processing** — reads items, processes them, and writes them in batches (owned by a sibling topic, out of scope here). 2. **Tasklet processing** — runs a single, arbitrary piece of code. The `Tasklet` interface (package `org.springframework.batch.core.step.tasklet`) is a **functional interface** with exactly one method: ```java RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception; ``` You put your custom logic in `execute()`. Because it's a `@FunctionalInterface`, you can also supply it as a lambda. ## When to use it Use a Tasklet when the step is a **single logical action** rather than iteration over many records: - Deleting or archiving temporary files at the start/end of a job - Calling a **stored procedure** or running a bulk `UPDATE` - Sending an email/notification, pinging a health endpoint - Decompressing an archive, moving/renaming files - Running an external OS command If instead you must read thousands of rows, transform each, and write them, you want the chunk model — not a Tasklet. ## How you wire it With the modern `StepBuilder` (Spring Batch 5, `spring-batch-core`): ```java @Bean Step cleanupStep(JobRepository repo, PlatformTransactionManager tx, Tasklet cleanupTasklet) { return new StepBuilder("cleanupStep", repo) .tasklet(cleanupTasklet, tx) .build(); } ``` `tasklet(...)` requires **both** the Tasklet and a `PlatformTransactionManager` — Spring wraps each `execute()` invocation in a transaction. ## The return value drives repetition `execute()` returns a `RepeatStatus`: - `RepeatStatus.FINISHED` — the step's work is done; do not call again. - `RepeatStatus.CONTINUABLE` — there is more to do; Spring will call `execute()` **again in a new transaction**. Returning `null` is treated as `FINISHED`. This loop-until-finished behavior lets you break large work into transactional chunks yourself (see the CONTINUABLE topic). ## Key parameters - `StepContribution` — lets you report item counts / exit status back to the framework and read/adjust the running step contribution. - `ChunkContext` — gives access to the `StepContext`, and through it the `StepExecution`, `ExecutionContext` (for state between restarts), and job parameters. ## Gotchas - **A Tasklet must be idempotent-aware for restart**: if it returns CONTINUABLE and the job fails midway, on restart the whole step re-runs from scratch unless you persist progress in the `ExecutionContext`. - **The transaction wraps the whole execute() call** — a long-running Tasklet holds a DB transaction open the entire time; keep it short or manage transactions yourself. - **Don't confuse it with chunk processing** — a Tasklet is not the place to loop over a JDBC ResultSet item-by-item if you want commit intervals and reader/writer semantics.

  • What are the two arguments passed to execute() and what is each for?
    StepContribution — to report item counts and influence exit status back to the framework; ChunkContext — to reach the StepContext, StepExecution, ExecutionContext, and job parameters.
  • Does a Tasklet run inside a transaction?
    Yes. Each execute() invocation is wrapped in a transaction managed by the PlatformTransactionManager you pass to StepBuilder.tasklet(); that's why the tx manager is a required argument.

saying these in an interview costs you the question

  • Saying a Tasklet is for looping over items one-by-one (that's the chunk model)
  • Thinking execute() runs without a transaction
  • Believing you don't need a PlatformTransactionManager to build a tasklet step

context

open as a page

Explain RepeatStatus.FINISHED versus RepeatStatus.CONTINUABLE returned from Tasklet.execute().

level: middleimportance: must knowfreq 60%

basics

~10 s

FINISHED means the Tasklet is done and won't be called again. CONTINUABLE means there's more work, so Spring calls execute() again in a new transaction. Returning null counts as FINISHED.

open as a page

What is MethodInvokingTaskletAdapter and when would you use it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

It's an adapter that turns any existing Spring bean method into a Tasklet, so you don't have to implement the Tasklet interface. You set the target object and the method name, and its return value can drive exit status.

open as a page

How does SystemCommandTasklet work and what must you configure to use it safely?

level: seniorimportance: should knowfreq 30%

basics

~20 s

SystemCommandTasklet runs an external OS command (like a shell script) as a batch step. You set the command, a timeout, and usually a working directory. It runs the command in a separate thread and checks the exit code.

open as a page

A cleanup Tasklet that returns CONTINUABLE to delete data in batches fails halfway. What determines whether the restarted job resumes correctly, and how do you design for it?

level: principalimportance: should knowfreq 20%

basics

~20 s

Because each CONTINUABLE pass commits its own transaction, completed batches stay deleted. On restart the whole step re-runs execute() from the start, so correctness depends on the work being idempotent or on progress saved in the ExecutionContext.

open as a page