How to use the current time in a Java Program?

135 Views Asked by At

Say, for example, I want to run the following program

double x = 15.6
System.out.println(x);

But I wanted to repeat the program until a certain time has elapsed, such as the following:

do{
double x = 15.6
System.out.println(x);
}while (current time is earlier than 12.00pm)

Even though the example is completely hypothetical, how would I make that do while loop so that the program would keep running over and over again until a certain time, say 3pm, or9.30pm.

If this is not possible, is there any way I can simulate this, by running the program every so many seconds, until that time has been reached?

2

There are 2 best solutions below

2
On BEST ANSWER

a) You usually don't need the code to actually run until a time has come - you wouldn't have any control over the amount of times the code executed this way. Regular code has to sleep sometimes, to give control to OS and other processes so that they don't clog the system with 100% CPU load. As such, actually running the code constantly is a wrong approach to 99% of the possible problems related to timings. Please describe the exact problem you want to solve using this code.

b) For those 99% of problems, use a Timer instance. Simple as that. https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html - schedule the task to run e.g. 1000 times a second, and check the time in each event, terminating the Timer instance when the time threshold has been exceeded.

For example, this code above will give you continuous execution of Do something part, every 1 second, until 16.11.2014 20:00 GMT. By changing delayMs you can easily achieve higher/lower time granularity. If you expect your code to be run more often than 1000/sec, you should probably use JNI anyway, since Java timers/clocks are known to have <10ms granularity on some (older) platforms, see How can I measure time with microsecond precision in Java? etc.

    Timer timer = new Timer();
    int delayMs = 1000; // check time every one second
    long timeToStop;
    try {
        timeToStop = new SimpleDateFormat( "DD.MM.YYYY HH:mm" ).parse( "16.11.2014 20:00" ).getTime(); // GMT time, needs to be offset by TZ
    } catch (ParseException ex) {
        throw new RuntimeException( ex );
    }
    timer.scheduleAtFixedRate( new TimerTask() {
        @Override
        public void run() {
            if ( System.currentTimeMillis() < timeToStop ) {
                System.out.println( "Do something every " + delayMs + " milliseconds" );
            } else {
                timer.cancel();
            }
        }

    }, 0, delayMs );

or you can use e.g. ExecutorService service = Executors.newSingleThreadExecutor(); etc. - but it's virtually impossible to give you a good way to solve your problem without explicitly knowing what the problem is.

19
On

Something like this

//get a Date object for the time to stop, then get milliseconds
long timeToStop = new SimpleDateFormat("DD:MM:HH:mm").parse("16:11:12:00").getTime();

//get milliseconds now, and compare to milliseconds from before
do {
//do stuff
} while(System.currentTimeMillis() < timeToStop)