G Boggs
G Boggs

Reputation: 391

How to run a fixed interval thread from start of app?

This may be a poorly worded title, but I am trying to gather data and statistics on my application from the very start of it. I am using JavaFX and I have a model class that will be dealing with all of the data and processing.

What I want is for that model class to start gathering the data (like runtime, thread count, mem usage...) from the moment the app starts. But I also want it to keep updating these values every second, which means I need it to run on some sort of ScheduledExecutorThread or something.

How can I do so that from the very start of this program, the model class will run the "update()" function every second?

Upvotes: 1

Views: 124

Answers (1)

rolfl
rolfl

Reputation: 17707

Any time you are looking to do fixed-interval opetations in Java you should be investigating the ScheduledExecutorService. In your case, something like:

private static final ScheduledExecutorService SERVICE = Executors.newScheduledThreadPool(1,
    new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread("Tick Thread", r);
            t.setDaemon(true);
            return t;
        }
    });

private static final AtomicReference<Controller> CONTROLLER = new AtomicReference<>();

public static final void setController(Controller c) {
    CONTROLLER.compareAndSet(null, c);
}

static {

    Runnable task = new Runnable() {
        public void run() {
            //do something each second....
            // call the 'update()' method:
            Controller c = CONTROLLER.get();
            if (c != null) {
                c.update();
            }
        }
    }

    // delay 1 second, repeat each second.
    service.scheduleAtFixedRate(task, 1, 1, TimeUnit.SECONDS);
}

You can take that, and put it in a Static initializer of the class, and you will get the system started the moment the class is loaded.... You will likely want the thread on the ExecutorService to be a Daemon thead... so you need a custom thread factory.....

The above code will start immediately, and will update the Controller, if there is one, every second.

The moment you create c controller, you can set the value using the static method.

Upvotes: 1

Related Questions