spring - 安排一个 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();
}
}
解决方案
由于该方法是在构造函数中调用的,因此在初始化 bean 时会调用它。所以我每次都必须重新启动我的应用程序
您不需要为此在每个计划中关闭/重新启动应用程序上下文。您可以将任何初始化代码移动到JobExecutionListener#beforeJob
更适合您的用例的代码中。
解决这个问题的另一种方法是创建一个 tasklet,它调用生成 json 文件的脚本(SystemCommandTasklet
例如),然后创建第二个步骤,使用 json 项目阅读器读取文件(文件名可以在两个步骤之间共享)执行上下文)。
在这两种情况下,都无需像当前那样在每个计划中关闭/重新启动应用程序上下文。
推荐阅读
- php - 按总分 ASC 排序
- javascript - 从 fetch 之外的其他地方调用在 fetch 中定义的函数
- android - 在具有相同分辨率和相同 ppi 的不同制造商设备中,图标和内容显示不相似
- reactjs - 如何在reactjs中对存储在上下文api中的数据执行搜索?
- reactjs - 从 FlatList 中删除项目失败,并显示“TypeError: (0, _activities.default) is not a function”
- linux - crontab 不会执行 shell 脚本
- assembly - 当前指令旁边的 RIP 相关加载会发生什么?缓存命中?
- r - 如何将轴线更改为箭头
- javascript - 如何计算有多少
- 项目在一个
- 带有条件的标签
- 项目在一个
- php - 在卡片 wordpress 中显示页面