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

41,652

Solution 1

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);

Solution 2

Take a look at the java.util.Concurrent API, in particular, you may be interested in the ScheduledExecutorService

Solution 3

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).

Share:
41,652
exit_1
Author by

exit_1

Updated on July 27, 2020

Comments

  • exit_1
    exit_1 almost 4 years

    I have been assigned on designing a java program on a linux machine that:

    1. Connects to a database
    2. reads a record
    3. retrieve certain information and send to Nagios according to a field known as 'threat_level'
    4. read next record and repeat step number 3 until all records have been read

    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.