spring-boot工程打包成了jar包的服务如何在执行单次任务就结束?
思路一: 先启动工程,再mvc调用一次请求执行结束再内部结束进程
思路二: 工程启动完成执行完任务以后立马结束
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
@Slf4j
public class StartupRunner implements CommandLineRunner {
@Autowired
MyService myService;
@Override
public void run(String... args) throws Exception {
log.info("startup runner");
log.info("args:{}",args);
myService.doJob();
log.info("task finished");
}
}
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
/**
* 应用启动入口.
*
*/
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@ComponentScans(value = { @ComponentScan(basePackages = "com..."),
@ComponentScan(basePackages = "com..."),
@ComponentScan(basePackages = "com...")})
public class MyApp {
@Bean
public ExitCodeGenerator exitCodeGenerator() {
return () -> 42;
}
public static void main( String[] args ) {
// SpringApplication.run(MyApp.class, args);
System.exit(SpringApplication
.exit(SpringApplication.run(MyApp.class, args)));
}
@Bean
public StartupRunner startupRunner(){
return new StartupRunner();
}
}
现在打包成jar包,执行并传入参数
java -jar myapp.jar --job=job1
结果输出
startup runner
args:--job=job1
task finished
思路三:
直接在任务执行完成以后调用System.exit方法
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
@Slf4j
public class StartupRunner implements CommandLineRunner {
@Autowired
MyService myService;
@Override
public void run(String... args) throws Exception {
log.info("startup runner");
log.info("args:{}",args);
myService.doJob();
log.info("task finished");
System.exit(0);
}
}