Quick revision
The short answer
A tasklet is a single piece of work that a step runs: we implement Tasklet.execute(StepContribution, ChunkContext), delete the files older than 7 days inside it, and return RepeatStatus.FINISHED. FINISHED tells Spring Batch the work is done, while CONTINUABLE asks it to call execute again, each call in its own transaction, which is how we process a big job in slices.
What to remember
In this answer, we wrote a Spring Batch 5 tasklet that deletes staging files older than 7 days, built its step with new StepBuilder("cleanup", jobRepository).tasklet(tasklet, transactionManager) and recorded its work with incrementWriteCount so the run history shows what it did. We saw that FINISHED ends the step while CONTINUABLE makes the step call execute again in a new transaction, which is how we split large work into slices, as long as the loop is tied to real progress. Finally, we saw that tasklets fit single actions and chunk steps fit item streams.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A tasklet is a single piece of work that a step runs: we implement Tasklet.execute(StepContribution, ChunkContext), delete the files older than 7 days inside it, and return RepeatStatus.FINISHED. FINISHED tells Spring Batch the work is done, while CONTINUABLE asks it to call execute again, each call in its own transaction, which is how we process a big job in slices.
Why this question is asked
Not every batch step reads and writes a stream of items. Many real jobs start or end with a single action: clean a folder, call a stored procedure, move a file to an archive, refresh a materialised view. Spring Batch models these as tasklet steps. Interviewers ask this question to check that we can write one correctly in Spring Batch 5, where the builders changed, and that we understand what the return value means, because CONTINUABLE is both a useful tool and a classic source of steps that never end. In this answer, we will recap what a tasklet is, write the cleanup tasklet, build the step and the job, report what it did, explain FINISHED and CONTINUABLE with an example, and decide when a tasklet is the right choice.
1A Quick Recap of Tasklet Steps
A Spring Batch step is either chunk-oriented, reading items, processing them and writing them in chunks, or tasklet-based. A tasklet step holds one object that implements the Tasklet interface, which has a single method: RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext).
StepContribution is where we record what this call did, such as how many items were written, so the numbers end up in the step's counters. ChunkContext gives access to the step context, the job parameters and the execution context. RepeatStatus, the return value, tells the step whether to call execute again. Every call to execute runs inside a transaction that the step opens and commits, which is why the step needs a transaction manager.
2Writing the Cleanup Tasklet
Our tasklet lists the staging folder, deletes regular files whose last modification time is more than 7 days ago, and records the count. The folder is passed in so that tests can point it at a temporary directory.
Notice the small choices. Files.list returns a stream that holds an open directory handle, so it must be closed, which the try-with-resources does. deleteIfExists avoids failing when another process removed the file a moment earlier. Using a Clock instead of Instant.now() lets a test set the date to any day it likes. And the cutoff is computed once at the start, so files do not change category halfway through the loop.
3Building the Step and the Job in Spring Batch 5
Spring Batch 5 removed the old StepBuilderFactory and JobBuilderFactory. We now create builders directly, passing the JobRepository, and the tasklet method takes the transaction manager explicitly.
Because we called incrementWriteCount, the run record shows that 42 files were removed. Without it the step would report zero for everything, and anyone looking at the history could not tell a run that cleaned 42 files from one that found nothing. The same counts feed Spring Batch's metrics, so a dashboard can show how much each run did. Spring Batch 6 adjusts some builder signatures, so check your version if you are on Spring Boot 4.
4RepeatStatus.FINISHED Versus CONTINUABLE
After each call, the step looks at the returned RepeatStatus. FINISHED means the tasklet's work is complete, so the step commits the transaction and ends. CONTINUABLE means there is more to do, so the step commits the current transaction, updates the step's records, and calls execute again in a new transaction. A null return is treated like FINISHED.
This turns a tasklet into a loop where each pass is a separate transaction. Suppose the staging folder held 200,000 old files. Instead of deleting them all in one call, we could delete 1,000 per call and return CONTINUABLE until a call finds nothing left. If the job stops after pass 150, the 150,000 files are already gone and their progress is recorded.
- Step startsopens the step execution
- Begin transaction
- Call tasklet.execute()deletes up to 1,000 files
- Commit and save countswrite count and execution context are stored
- Returned CONTINUABLE?Yesgo back to begin transactionNostep ends COMPLETED
5 steps in order. Play them, or step through them one at a time.
But there is a catch. The loop only ends when the tasklet returns FINISHED, so the condition must be one that is guaranteed to become true. A tasklet that returns CONTINUABLE because 'there were errors' and retries the same failing file forever produces a step that never ends. Always tie CONTINUABLE to measurable progress, such as 'this call did some work'.
5When a Tasklet Is the Right Choice
A tasklet fits a single action whose work does not naturally break into independent items: deleting or moving files, calling a stored procedure, running one SQL statement, sending one notification, or checking that an input file has arrived. A chunk step fits a stream of items that each need reading, processing and writing, such as loading the lines of a CSV into a table, because it gives us chunked commits, skip and retry rules, restart from the last committed chunk and per-item counters for free.
If we find ourselves writing a tasklet that reads records, loops over them, transforms each one and writes them out, we are rebuilding a chunk step by hand, without its restart and skip support. That is the signal to switch.
6Follow-up questions
Is deleting files transactional just because execute runs in a transaction?
No. The transaction covers database work done through the step's transaction manager, plus the step's own metadata updates. Deleting a file is a file system action that a database rollback cannot undo. That is why a cleanup tasklet should be safe to repeat: if it fails halfway and runs again, it simply deletes the remaining old files.
How would you test this tasklet?
Create a temporary directory with JUnit's @TempDir, add files and set their modification times with Files.setLastModifiedTime, give the tasklet a fixed Clock, and call execute with a StepContribution created from a test StepExecution, for example from MetaDataInstanceFactory in spring-batch-test. Then assert which files remain and that the write count is what we expect.
Can a tasklet read job parameters?
Yes. chunkContext.getStepContext().getJobParameters() returns them as a map, or we can make the tasklet a @StepScope bean and inject a parameter with @Value("#{jobParameters['retentionDays']}"), which is cleaner when the retention period should come from the run.
7Conclusion
In this answer, we wrote a Spring Batch 5 tasklet that deletes staging files older than 7 days, built its step with new StepBuilder("cleanup", jobRepository).tasklet(tasklet, transactionManager) and recorded its work with incrementWriteCount so the run history shows what it did. We saw that FINISHED ends the step while CONTINUABLE makes the step call execute again in a new transaction, which is how we split large work into slices, as long as the loop is tied to real progress. Finally, we saw that tasklets fit single actions and chunk steps fit item streams.
Open with
I would implement the Tasklet interface. In execute, which gets a StepContribution and a ChunkContext, I compute the cutoff once as now minus seven days, using an injected Clock so it is testable, then list the staging directory in a try-with-resources, and delete every regular file whose last modified time is before the cutoff, with deleteIfExists so a file that disappeared does not fail the step.
Then, if they want more
I record the number with contribution.incrementWriteCount, so the run history and metrics show how many files were removed, and I return RepeatStatus.FINISHED. The step is built in Spring Batch 5 style: new StepBuilder with the name cleanup and the job repository, then tasklet with my tasklet and the transaction manager, then build, and a JobBuilder that starts with it.
FINISHED tells the step the work is done. CONTINUABLE tells it to commit and call execute again in a new transaction, which is useful for slicing big work, say a thousand files per call until nothing is left, so progress is committed along the way. The condition must be tied to real progress, or the step never ends.
Tasklets fit single actions like this; for a stream of records I would use a chunk step.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Boot 4
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Batch reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a tasklet step in Spring Batch 5 that deletes staging files older than 7 days, and...": https://scrivio-interview-library.netlify.app/spring-boot/spring-batch/a9424cdf5f/