spring boot 手动启动停止任务
时间: 2023-07-29 08:08:01 浏览: 86
Spring Boot 提供了一个 TaskExecutor 接口,可以手动启动和停止任务。下面是一个简单的示例代码:
首先,创建一个任务类:
```java
import org.springframework.stereotype.Component;
@Component
public class MyTask implements Runnable {
private volatile boolean running = false;
@Override
public void run() {
running = true;
while (running) {
// 执行任务逻辑
}
}
public void stop() {
running = false;
}
}
```
然后,在启动类中注入 TaskExecutor,手动启动和停止任务:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.task.TaskExecutor;
@SpringBootApplication
public class MyApp {
@Autowired
private TaskExecutor taskExecutor;
@Autowired
private MyTask myTask;
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
public void startMyTask() {
taskExecutor.execute(myTask);
}
public void stopMyTask() {
myTask.stop();
}
}
```
启动任务:
```java
MyApp app = SpringApplication.run(MyApp.class, args);
app.startMyTask();
```
停止任务:
```java
app.stopMyTask();
```
阅读全文