Getting Java to sleep between loops, sleep time designated by command line on Linux Getting Java to sleep between loops, sleep time designated by command line on Linux linux linux

Getting Java to sleep between loops, sleep time designated by command line on Linux


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=60000Then 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).