package com.example.sjkbf;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.File;
import java.io.IOException;
import java.util.Date;

@SpringBootApplication()

public class SjkbfApplication {

    private static ConfigurableApplicationContext context;

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



        // 添加自定义关闭钩子，打印触发源
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("=====================================");
            System.out.println("=== 自定义ShutdownHook触发！开始定位原因 ===");
            System.out.println("触发时间：" + new java.util.Date());
            System.out.println("当前线程：" + Thread.currentThread().getName());
            // 打印所有线程的栈轨迹，找到触发关闭的源头
            Thread.getAllStackTraces().forEach((thread, stackTraces) -> {
                // 只打印关键线程（减少日志量）
                if (thread.getName().contains("ShutdownHook") || thread.getName().contains("main")
                        || thread.getName().contains("Task") || thread.getName().contains("Timer")) {
                    System.out.println("\n线程名称：" + thread.getName() + " (状态：" + thread.getState() + ")");
                    for (StackTraceElement elem : stackTraces) {
                        System.out.println("\t" + elem);
                    }
                }
            });
            System.out.println("=== ShutdownHook触发原因定位结束 ===");
            System.out.println("=====================================");


            System.out.println("=== 应用触发关闭，开始重启上下文 ===");
            // 关闭当前上下文
            context.close();
            // 重新启动上下文
            context = SpringApplication.run(SjkbfApplication.class, args);
        }, "Custom-Exit-Detector"));
    }




}
