If you only need a Timer
, you can register a DefaultMeterObservationHandler
and disable the LongTaskTimer
creation (see its ctor). If you use Spring Boot, it auto-configures the handler for you and lets you disable LongTaskTimer
with a property.
I also think that there might be a misunderstanding here, please read the docs first. I'm mostly curious why you want to do this:
At the end of this run I would like to know the start time and end time. The completion time is to be passed to a subsequent method call.
Since with the Observation API, you should not do such a thing, these things should be done in ObservationHandler
s (again, see the docs).
If you want to produce your own output and you need the start/end time for that, you can create and register a handler like this:
public class CustomHandler implements ObservationHandler<Observation.Context> {
@Override
public void onStart(Observation.Context context) {
// I recommend using an enum or class instead of a String key, something that the compiler can verify
context.put("startTime", System.nanoTime());
}
@Override
public void onStop(Observation.Context context) {
long startTime = context.getRequired("startTime");
long stopTime = System.nanoTime();
}
@Override
public boolean supportsContext(Observation.Context context) {
return true;
}
}
See the docs.
If you want to get this information after the Observation (not recommended), you can create and register a handler like the above (you should put stopTime
into the Context in onStop
) and then:
Observation observation = Observation.createNotStarted("something", observationRegistry)
observation.observe(() -> doSomething(observation));
long startTime = observation.getContextView().getRequired("startTime");
long stopTime = observation.getContextView().getRequired("stopTime");
Why would I measure it on my own or use a LongTaskTimer when the normal Timer has everything I need?
I'm afraid you are mixing your own use-case (though I'm not really sure what you are trying to do) with the use-case of the other question. There the person who asked already had a LongTaskTimer
since they used DefaultMeterObservationHandler
already. You don't need to, its up to you.
In the previous question it is mentioned not to use reflection to get the Timer - but why is it not public?
Because you don't need it, also you migh not even have a Timer
or you might use it outside of an Observation
. Timer
was created long before the Observation API and I'm not aware anyone needed the internal representation of Timer.Sample
so far.
Please try to explain what you are exactly trying to do since I'm afraid we have an XY problem: https://xyproblem.info