Spring boot immediate return result fails to execute function

user1007522 :

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());
}
Simon Martinelli :

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:

  1. 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.

Source: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-task-execution-scheduling

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=329707&siteId=1