简体   繁体   English

我们如何才能在 java 的 main 方法中只执行一次特定的代码行?

[英]How can we execute particular line of code only once in main method in java?

I have a jar file in which there is the main method, in that main method I have several lines of code, in which I want to execute specific code only once in jar file execution and other code should be running as many time main method is called by jar file.我有一个 jar 文件,其中有 main 方法,在那个 main 方法中我有几行代码,其中我只想在 jar 文件执行中执行特定代码一次,其他代码应该运行多次 main 方法由 jar 文件调用。 Here is the image of the code the first line UIConfigureJson configJson = new UIConfigureJson();这是第一行代码的图像 UIConfigureJson configJson = new UIConfigureJson(); run only one time in jar file execution because this jar runs main method at every 15 minutes.在 jar 文件执行中只运行一次,因为此 jar 每 15 分钟运行一次 main 方法。 so this line should be run only one time.所以这条线应该只运行一次。

If you are trying to persist state between application instances (ie if the code needs to "remember" something between different runs), you need to save it to a file.如果您尝试在应用程序实例之间保留 state(即,如果代码需要在不同运行之间“记住”某些内容),则需要将其保存到文件中。

In your case, you should create a file the first time the main method is called and check if that file exists before running this line (and the file creation code)在您的情况下,您应该在第一次调用 main 方法时创建一个文件,并在运行此行之前检查该文件是否存在(以及文件创建代码)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM