Reputation: 8118
I want to return immediate the result of a database query but I want to start a different thread that does some things.
Now I tried with an Executor like this:
Executors.newScheduledThreadPool(1).schedule(
() -> fooFunction(),
1, TimeUnit.SECONDS
);
but the function is not executed after the method returns.
Complete code:
@Override
@Transactional
public FooDto updateInfo(UpdateTaskDto updateTask) {
// updating the entity
Executors.newScheduledThreadPool(1).schedule(
() -> fooFunction(),
1, TimeUnit.SECONDS
);
return FooDto()
}
Where fooFunction is just a function that saves something to the database and returns void.
This updateInfo function is inside a @Service annotated class.
Why is this not working?
EDIT:
@Transactional
@Override
public update() {
if (hasStartDateChanges || hasEndDateChanges) {
taskExecutor.execute(() -> {
setNotifications(changedTaskDto, NotificationType.TASK_UPDATE_TIME, true, taskEntity.getProject().getCompany().getId(), currentUser);
});
}
}
public void setNotifications(TaskDto task, NotificationType type, boolean visibleForClient, Long companyId, UserDto currentUser) {
ProjectEntity projectEntity = repository.findBy(task.getProjectId());
}
Upvotes: 1
Views: 383
Reputation: 36223
You can simply inject the TaskExecutor or TaskScheduler and use it:
@RestController
@RequestMapping("/demo")
public static class DemoRestController {
private final TaskExecutor taskExecutor;
public DemoRestController(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
@GetMapping
public String get() {
taskExecutor.execute(() -> {
System.out.println("Hello from Task");
});
return "hello";
}
}
From the docs:
- Task Execution and Scheduling In the absence of an Executor bean in the context, Spring Boot auto-configures a ThreadPoolTaskExecutor with sensible defaults that can be automatically associated to asynchronous task execution (@EnableAsync) and Spring MVC asynchronous request processing.
Upvotes: 3