使用 spring boot 在后台运行进程

Ray*_* En 5 java spring-boot workmanagertaskexecutor

如何使用 Spring Boot 在后台运行某些进程?这是我需要的一个例子:

@SpringBootApplication
public class SpringMySqlApplication {

    @Autowired
    AppUsersRepo appRepo;

    public static void main(String[] args) {
        SpringApplication.run(SpringMySqlApplication.class, args);

        while (true) {
            Date date = new Date();
            System.out.println(date.toString());
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

kim*_*y82 10

您可以使用异步行为。当您调用该方法并且当前线程确实等待它完成时。

像这样创建一个可配置的类。

@Configuration
@EnableAsync
public class AsyncConfiguration {

    @Bean(name = "threadPoolTaskExecutor")
    public Executor threadPoolTaskExecutor() {
        return new ThreadPoolTaskExecutor();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在一个方法中使用:

@Async("threadPoolTaskExecutor")
public void someAsyncMethod(...) {}
Run Code Online (Sandbox Code Playgroud)

查看spring 文档以获取更多信息


And*_*hle 8

您可以只使用@Scheduled-Annotation。

@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
     log.info("The time is now " + System.currentTimeMillis()));
}
Run Code Online (Sandbox Code Playgroud)

https://spring.io/guides/gs/scheduling-tasks/

Scheduled 注释定义特定方法何时运行。注意:此示例使用 fixedRate,它指定从每次调用的开始时间开始测量的方法调用之间的间隔。

  • 你为什么要这样做?在您的示例中,您可以将速率设置为 3000,因此您不需要执行 TimeUnit.SECONDS.sleep(3); 不再这样了,因为你的方法每 3000 毫秒执行一次。 (3认同)
  • 感谢 ui 想将fixedRate更改为无穷大 (2认同)