首页 > 解决方案 > 安排一个 Spring 批处理作业以每 4 小时重新启动我的应用程序

问题描述

我想每 4 小时安排一次作业,以每 4 小时重新启动我的 spring 批处理应用程序。我正在使用下面的代码,但它只是安排我的作业。我在应用程序启动时运行的方法很少。这些方法没有得到预定的

@EnableScheduling
public class App {
    private static ConfigurableApplicationContext context;

    private static final Logger logger = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        BasicConfigurator.configure();
        context = SpringApplication.run(App.class, args);

    }

    @Scheduled(cron = "0 0 0/4 * * * ")
    public static void restart() {
        ApplicationArguments args = context.getBean(ApplicationArguments.class);
        logger.info("##### Scheduler Started #####"+System.currentTimeMillis());

        Thread thread = new Thread(() -> {
            context.close();
            logger.info("***Context Closed***"+System.currentTimeMillis());
            context = SpringApplication.run(App.class, args.getSourceArgs());
            logger.info("###### Context  Restarted "+ 
            System.currentTimeMillis());
        });

        thread.setDaemon(false);
        thread.start();
    }
 }

标签: springspring-bootspring-batchquartz-schedulertaskscheduler

解决方案


由于该方法是在构造函数中调用的,因此在初始化 bean 时会调用它。所以我每次都必须重新启动我的应用程序

您不需要为此在每个计划中关闭/重新启动应用程序上下文。您可以将任何初始化代码移动到JobExecutionListener#beforeJob更适合您的用例的代码中。

解决这个问题的另一种方法是创建一个 tasklet,它调用生成 json 文件的脚本(SystemCommandTasklet例如),然后创建第二个步骤,使用 json 项目阅读器读取文件(文件名可以在两个步骤之间共享)执行上下文)。

在这两种情况下,都无需像当前那样在每个计划中关闭/重新启动应用程序上下文。


推荐阅读