Thomson Mathew
Thomson Mathew

Reputation: 439

How to use StepListenerSupport

I am trying to stop a running job based on timeout value. I am following a post found here, but I am not sure how you add this listener.

Here is the listener implementation

public class StopListener extends StepListenerSupport{
    public static final Logger LOG = LoggerFactory.getLogger(StopListener.class);
    private static final int TIMEOUT = 30; 
    private StepExecution stepExecution;

    @Override
    public void beforeStep(StepExecution stepExecution) {
        this.stepExecution = stepExecution;
    }

    @Override
    public void afterChunk(ChunkContext context) {
        if (timeout(context)) {
            this.stepExecution.setTerminateOnly();
        }
    }

    private boolean timeout(ChunkContext chunkContext) {
        LOG.info("----- TIMEOUT-----");
        Date startTime = chunkContext.getStepContext().getStepExecution().getJobExecution().getStartTime();
        Date now = new Date();
        return Duration.between(startTime.toInstant(), now.toInstant()).toMinutes() > TIMEOUT;
    }

}

Here is my step

@Bean
public Step dataFilterStep() {
    return stepBuilderFactory.get("dataFilterStep")
            .<UserInfo, UserInfo> chunk(10)
            .reader(dataFilterItemReader())
            .processor(dataFilterItemProcessor())
            .writer(dataFilterWriter())
            .listener(new StopListener())             
            .build();
}

But I am getting error saying "The method listener(Object) is ambiguous for the type SimpleStepBuilder<UserInfo,UserInfo>". A help would be really appreciated!

Upvotes: 0

Views: 513

Answers (1)

Mahmoud Ben Hassine
Mahmoud Ben Hassine

Reputation: 31600

On one hand, StepListenerSupport is a polymorphic object, it implements 7 interfaces. On the other hand, the step builder provides several overloaded .listener() methods to accept different types of listeners. That's why when you pass your StopListener in .listener(new StopListener()), the type of listener is ambiguous.

What you can do is cast the listener to the type you want, something like:

.listener(((ChunkListener) new StopListener()))

However, by following the principle of least power [1][2], I would recommend changing your StopListener to implement only the interface required for the functionality. In your case, you seem to want to stop the job after a given timeout in afterChunk, so you can make your listener implement ChunkListener and not extend StepListenerSupport.


Upvotes: 1

Related Questions