Saurabh Kumar
Saurabh Kumar

Reputation: 16651

i want to launch a class method periodically using spring

i have the following code.

@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {
@Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(50);
        executor.setQueueCapacity(10000);
        executor.setThreadNamePrefix("Executor-");
        executor.initialize();
        return executor;
    }
}

and if i want to run the recommend method after every certain interval of time. What can be the java spring bean configuration way to do that.?

public class UserBrandsRecommender {


    public List<RecommendedItem> recommend(Long userId, int number) throws TasteException{

    }
}

Upvotes: 1

Views: 325

Answers (1)

cliff.meyers
cliff.meyers

Reputation: 17734

You should look into the @Scheduled annotation. For example:

@Scheduled(fixedDelay=5000)
public void doSomething() {
    // something that should execute periodically
}

You'll probably need to create a new Spring bean with a method similar to above. The bean could have the UserBrandsRecommender injected into it. The new bean will need to implement some logic to pass proper values for the "userId" and "number" parameters to the "recommend" method.

More information here:

http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/htmlsingle/#scheduling-annotation-support

Upvotes: 1

Related Questions