SpringBoot实现定时重启项目

现在有一个需求,是定时任务执行扫描,判断如果端口有变化,需要重启项目。思路是通过关闭应用程序上下文并从头创建一个新上下文来重新启动应用程序。具体代码如下:

1. 启动类定义重启方法

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * @author: 
 * @date: 2023-02-03 14:20
 * @description: agent的启动类
 */
@SpringBootApplication
public class AgentApplication {

    private static ConfigurableApplicationContext context;

    public static void main(String[] args) {
        context = SpringApplication.run(AgentApplication.class, args);
    }

    /**
     * 重启服务
     */
    public static void restart() {
        ApplicationArguments args = context.getBean(ApplicationArguments.class);
        Thread thread = new Thread(() -> {
            context.close();
            context = SpringApplication.run(AgentApplication.class, args.getSourceArgs());
        });
        // 设置非守护线程
        thread.setDaemon(false);
        thread.start();
    }
}

2. 定时任务调用代码

import com.wrdxa.agent.AgentApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * @author: 
 * @date: 2023-02-03 16:19
 * @description: 定时任务的类
 */
@Configuration
@EnableScheduling
public class ScheduleTask {

    /**
     * 每隔1分钟执行一次查询,如果监测有变化,则进行重启
     */
    @Scheduled(cron = "*/30 * * * * ?")
    private void configureTasks() {
        System.out.println("开始重启");
        AgentApplication.restart();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值