spring-boot工程打包成jar包如何启动执行一次任务后就退出

15 篇文章 1 订阅

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);
    }
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值