gpt4 book ai didi

java - spring boot 立即返回结果执行失败函数

转载 作者:行者123 更新时间:2023-11-29 04:09:09 24 4
gpt4 key购买 nike

我想立即返回数据库查询的结果,但我想启动一个不同的线程来做一些事情。

现在我尝试使用这样的执行器:

  Executors.newScheduledThreadPool(1).schedule(
() -> fooFunction(),
1, TimeUnit.SECONDS
);

但是方法返回后函数并没有执行。

完整代码:

@Override
@Transactional
public FooDto updateInfo(UpdateTaskDto updateTask) {
// updating the entity

Executors.newScheduledThreadPool(1).schedule(
() -> fooFunction(),
1, TimeUnit.SECONDS
);

return FooDto()
}

其中 fooFunction 只是一个将某些内容保存到数据库并返回 void 的函数。

此 updateInfo 函数位于 @Service 注释类中。

为什么这不起作用?

编辑:

@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());
}

最佳答案

您可以简单地注入(inject) TaskExecutor 或 TaskScheduler 并使用它:

@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";
}
}

来自文档:

  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.

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

关于java - spring boot 立即返回结果执行失败函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56151384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com