I'm learning Java on my own and I'm stuck with the following problem. I scheduled my code to run for every 120 seconds and my issue here is that can't find the way to update LocalDateTime variable now outside of the run() method. I have a private static class called Date and I'm using this so I'm able to use this variables in other parts of the code that need to use the date at the same time.
public class Test{
private static class Date {
//This wont update every 120 seconds
private static final LocalDateTime now = LocalDateTime.now();
private static final DateTimeFormatter archive = DateTimeFormatter.ofPattern("yyyy MM dd HH:mm");
}
public Test(int seconds) {
timer = new Timer();
timer.schedule(new APICallerTask(), 0,seconds * 1000L); }
static class APICallerTask {
public void run() {
//This will update every 120 seconds
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter archive = DateTimeFormatter.ofPattern("yyyy MM dd HH:mm");}
}
public static void main(String[] args) {
new Test(120);
}
}
I'm sorry if this is a dumb question but I'm not being able to figure it out.
Any help is appreciated.
Thanks in advance.
As seen in correct Answer by Kanshyn,
LocalDateTimeis immutable. You need to store a fresh new instance when you want a new value.Also,
LocalDateTimeis the wrong class here. TheLocalDateTimeclass lacks the context of an offset-from-UTC or a time zone.When tracking a moment, a specific point in the timeline, use
Instant,OffsetDateTime, orZonedDateTime.In your case, probably best to use
Instantin your data model. When presenting to user, adjust to their expected time zone.Generate text from that
ZonedDateTimeby usingDateTimeFormatter. Automatically localize by callingZonedDateTime.ofLocalizedDateTime. Search Stack Overflow to learn more as this has been covered many times already.Study The Java™ Tutorials by Oracle Corp., free of cost.
See the section on date-time handling with java.time here.
Java comes with two classes named
Date. I suggest using another name to avoid confusion.No need to make your task class
static.Try to resist the urge to use that
staticlabel. As a beginner, you'll almost always be usingstaticin a wrong or less-than-optimal fashion. Code withstaticis not object-oriented.The
TimerandTimerTaskclasses are legacy, as noted in their Javadoc. Best to use the Executors framework in Java 5+. See The Java™ Tutorials.A
ScheduledExecutorServiceruns tasks repeatedly.For that shutdown boilerplate, see ExecutorService Javadoc.
Example code
We define an app to hold a reference to latest recorded moment. Because we expect to access this reference across threads, we use
AtomicReferencefor thread-safety.Our task is a nested class,
UpdateMomentTask. That class implementsRunnable, which means it promises to implement a method namedrun. TheScheduledExecutorServicecalls thatrunmethod on our behalf.On each execution of its
runmethod, we capture the current moment by instantiating a newInstantobject. Our task then stores a reference to that object as the payload of our app’sAtomicReferencevariable namedmoment.Notice no
staticanywhere (exceptmain).When run: