Skip to content
Advertisement

Making a static final Json object in Java

I am currently building a Java Vertx application that executes a task periodically.

This application is executes a certain logic and is supposed to return a value in a Json format.

The logic seems to work and I don’t have a problem getting the desired value in the log, but I have trouble returning that value.

public void getNum(RoutingContext context){

Timer time = new Timer();
ScheduledTask st = new ScheduledTask();
time.schedule(st, 0, 500);
JsonObject jo = st.getJo();
if(!jo.toString().equals("{}")){
  log.info("print json" + jo);
  context.response().putHeader("content-type", "application/json").setStatusCode(200).end(jo.encodePrettily());
}

And the code for scheduled task looks something like this.

public class ScheduledTask extends TimerTask {
    JsonObject jo = new JsonObject();
    public void run() {
       
      try {
        //logic

        jo.put("file", split[0]);
        jo.put("recogTime", split[1]);
        jo.put("number", split[2]);
        log.info(jo.encodePrettily());
      }catch (Exception e){
        e.printStackTrace();
        log.info("Error.Running.1stCMD");
      }
    }

  }

If I remove the if statement in my getNum method, it seems to return an empty json, so I am guessing that it is returning the initialized value of jo.

Would there be a way for me to return the desired value?

Thank you in advance!!

Advertisement

Answer

First thing:

time.schedule(st, 0, 500); -> This will only schedule but execute somewhere in future.

JsonObject jo = st.getJo(); -> Immediately after returning from previous call you are doing get(). The schedule function would not have run till then.

Second:

If you are using Vert.x Do not use java Timer. You can use Vertx provided functions

setPeriodic() -> To run again and again at scheduled interval. setTimer() -> To run once at scheduled interval.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement