简体   繁体   English

使计时器在属性文件中可配置

[英]Making timer configurable in properties file

I have a java program where I wrote a scheduler, or a timer where once it starts running. 我有一个Java程序,在其中编写了调度程序,或者在计时器开始运行时编写了计时器。 It will call the function every N minutes interval indefinitely. 它将每隔N分钟无限期调用一次该函数。 For now, I set N to 5 minutes. 现在,我将N设置为5分钟。

I want to sent out this program in a form of jar file along with some sort of properties file where the tester or anyone else can configure N; 我想以jar文件的形式连同某种属性文件一起发送该程序,测试人员或其他任何人都可以在其中配置N; so it's much more convenient and I do not have to change in the code itself. 因此它更加方便,而且我不必更改代码本身。

This is an example: 这是一个例子:

public void schedule() throws Exception {

    Timer t=new Timer();
    t.scheduleAtFixedRate(
        new TimerTask() {
            @Override
            public void run() {
              // System.out.println("HELEOELE");

                try {
                    test.index();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },
      0,
        300000);
}

In this case, N = 300000. 在这种情况下,N = 300000。

I am not too familiar with jar file but I do have a properties file with db connection created. 我对jar文件不太熟悉,但是我确实创建了带有数据库连接的属性文件。

This is how I called the properties: 这就是我所谓的属性:

 Properties props=new Properties();


        InputStream in = getClass().getResourceAsStream("/config.properties");

        props.load(in);
        in.close();
        int value=Integer.parseInt(props.getProperty("value"));

So I would appreciate is there any way to do this? 因此,我将有任何办法做到这一点?

You can read the properties file from the classpath in case it is present in your jar only. 您可以从类路径中读取属性文件,以防它仅存在于jar中。

Refer this: Load properties file in JAR? 请参考以下内容: 在JAR中加载属性文件?

But, if you wan't to store the properties file out of the jar and be able to make changes in it, then there are multiple options : 但是,如果您不希望将属性文件存储在jar之外,并且能够在其中进行更改,那么有多种选择:

  • store it on the file system at a specified location from where your code reads it. 将其存储在文件系统中代码从其读取的指定位置。

  • instead of a properties file, you can also have a system property defined, which stores the required value. 除了属性文件,您还可以定义一个系统属性,该属性存储所需的值。 But, you would have to restart your container every time you change the value. 但是,每次更改该值时,都必须重新启动容器。

  • you could also consider reading this value directly from the database (optionally loading it into an in-memory cache). 您也可以考虑直接从数据库中读取此值(可选地将其加载到内存中的缓存中)。 But, here, another API would needed to make changes in the database. 但是,这里需要另一个API来对数据库进行更改。

  • Store it outside the jar. 存放在罐子外面。 Refer the following link Read properties file outside JAR file 请参考以下链接在JAR文件之外读取属性文件

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

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