Skip to content

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("{}")){"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 {

        jo.put("file", split[0]);
        jo.put("recogTime", split[1]);
        jo.put("number", split[2]);;
      }catch (Exception e){


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!!



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.


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.