Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 971
exit_1 Avatar asked Jul 26 '12 19:07

exit_1


3 Answers

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);
like image 88
Tomasz Nurkiewicz Avatar answered Oct 21 '22 21:10

Tomasz Nurkiewicz


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

like image 25
MadProgrammer Avatar answered Oct 21 '22 20:10

MadProgrammer


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

like image 21
Jeremy Brooks Avatar answered Oct 21 '22 20:10

Jeremy Brooks