I have been assigned on designing a java program on a linux machine that:
Now, I needed to get this to run every few minutes; so what my partner did was create a script that uses a loop to run the program, sleeps a few minutes, and repeat.
Recently, my boss told us that its good but would like the whole procedure to be completely self contained in java; meaning that it loops and sleeps within java. On top of that, he would like to have the sleep duration be determined by command line each time that the program is run.
I did some research and it seems that using Thread.sleep() is inefficient in certain circumstances and I cannot tell if this is one of them or not. Also, I am still unclear on how to have the sleep time be determined via command line upon running the program. I can provide the code if necessary.
Thread.sleep()
is just fine, especially when you want to sleep for "few minutes":
public class Main {
public static void main(String[] args) throws InterruptedException {
final int sleepSeconds = Integer.parseInt(args[0]);
while(true) {
//do your job...
Thread.sleep(sleepSeconds * 1000);
}
}
}
Thread.sleep()
might be inefficient or not precise enough in millisecond time ranges, but not in your case. But if you want the process to run in the same frequency (as opposed to with fixed delay), consider:
final long start = System.currentTimeMillis();
//do your job...
final long runningTime = System.currentTimeMillis() - start;
Thread.sleep(sleepSeconds * 1000 - runningTime);
This is important of "do your job" part might take significant amount of time and you want the process with exact frequency.
Also for readability consider TimeUnit
class (uses Thread.sleep()
underneath):
TimeUnit.SECONDS.sleep(sleepSeconds);
Take a look at the java.util.Concurrent
API, in particular, you may be interested in the ScheduledExecutorService
Set a system property on the command line when the program is started: -Dmy.sleep.time=60000 Then get that parameter: long mySleepTime = System.getProperty("my.sleep.time");
Look at the Executor framework. The ScheduledExecutorService has a scheduleWithFixedDelay that will probably do what you want (run your code with a delay in between executions).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With