-1

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
  • 1
    Just keep in mind that such a code would be very wasteful of resource. Use Thread.Sleep in the while loop or even better take a look at the timer class if that is what you want to accomplish. docs.oracle.com/javase/7/docs/api/java/util/Timer.html stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java Commented Nov 16, 2014 at 17:15
  • Even though the example is completely hypothetical is the main problem here. You can't solve an imaginary problem with real-life tools. Please provide a more detailed description of what you're trying to achieve by running the code constantly - the example you provided would result in 100% CPU load and unstable code execution, due to e.g. reaching maximum Java/OS console throughput etc., while doing no sensible job at the same time. Commented Nov 16, 2014 at 18:05

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Quite simply, I have a program, that i want to start running when I press 'Run', and to keep on running until the time is 4.30pm. What other information do you need?
what is the program functionality - what you want to achieve by running it. You're probably trying to use wrong tool for your task. By default, the application will run for as long as you don't return from the main() method; by e.g. creating a JFrame, you can keep the app open for as long as you wish. Also, what is the time granularity you want to achieve, i.e. how often do you want to check if the expected time has elapsed? Is 1 second enough?
1

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)

19 Comments

I need this program to run all day. Would it be a possibility to just have a while loop outside all of the program that would make it run to infinity until someone terminates it?
if by "fixing" you mean reverting to the original, wrong version - yes, I agree, you've certainly "fixed" it. Pity you hadn't understood the rationale behind my comment.
@vaxquis ive reverted to the original, and replaced Date with System.currentTimeMillis is that not what you wanted?
new SimpleDateFormat("HH:mm").parse("12:00") comes up with red underlines
import java.text.SimpleDateFormat; public class testing { public static void main (String[] args){ //get a Date object for the time to stop, then get milliseconds long timeToStop = new SimpleDateFormat("HH:mm").parse("12:00").getTime(); //get milliseconds now, and compare to milliseconds from before do{ //do stuff } while(System.currentTimeMillis() < timeToStop); }}
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.