'Can you use an infinite loop to run a program continuously using Java?
I have a question that I have researched that I did not find any compelling answers to. If you want to run a program in a loop every 2 hours or so, and of course, I know that anyone can use windows scheduler or something like that, will running the program in an infinite loop and using the "continue" statement every 2 hours or so prevent it from breaking (StackOverflow)?
Solution 1:[1]
Something simple/primitive like this will get you started:
public static void main(String[] args)
while (true) {
try {
// do something
Thread.sleep(TimeUnit.HOURS.toMillis(2));
} catch Exception e {
e.printStackTrace();
}
}
}
Solution 2:[2]
Theoretically you can do this. But there are multiple ways to do it much better. First even if you want to do infinite loop do it in a separate thread. But the simplest and standard way to do something like this is to write some class that implements Runnable interface, place your "do something" code into its method run()
and use ScheduledExecutorService to schedule your task for every 2 hours. The ScheduledExecutorService
you can get from Executors.newScheduledThreadPool(int corePoolSize) method. On a side note, There is a Open source library (written by me) that can simplify sleep delay code for you instead of
try {
// do something
Thread.sleep(TimeUnit.HOURS.toMillis(2));
} catch Exception e {
e.printStackTrace();
}
you can just write something like this:
private static final TimeInterval TWO_HOURS = new TimeInterval(2L, TimeUnit.HOURS);
...
//Do something
TimeUtils.sleepFor(TWO_HOURS);
The Exception is handled inside. Here is the Javadoc for TimeUtils class. The library is called MgntUtils and could be taken as Mavien Artifact or from Github (including source code and Javadoc)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bohemian |
Solution 2 | Michael Gantman |