-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?

Roman C
  • 49,761
  • 33
  • 66
  • 176
user296950
  • 35
  • 1
  • 8
  • 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. https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html http://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java – Icy Creature Nov 16 '14 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. –  Nov 16 '14 at 18:05

2 Answers2

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.

Community
  • 1
  • 1
  • 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? – user296950 Nov 16 '14 at 17:35
  • *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? –  Nov 16 '14 at 17:40
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)
Hamzah Malik
  • 2,540
  • 3
  • 28
  • 46
  • 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? – user296950 Nov 16 '14 at 17:23
  • 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. –  Nov 16 '14 at 17:24
  • @vaxquis ive reverted to the original, and replaced Date with System.currentTimeMillis is that not what you wanted? – Hamzah Malik Nov 16 '14 at 17:25
  • new SimpleDateFormat("HH:mm").parse("12:00") comes up with red underlines – user296950 Nov 16 '14 at 17:26
  • 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); }} – user296950 Nov 16 '14 at 17:28
  • @user296950 you cant expect people to solve everything. Read what the error is, why its underlined – Hamzah Malik Nov 16 '14 at 17:28
  • @HamzahMalik it's *better*, but that doesn't mean it's *fixed*... the main problem with this code is still present. –  Nov 16 '14 at 17:28
  • @vaxquis how would one use thread.sleep? He wants the program to run indefinetly until 12pm. Where does it need to sleep? – Hamzah Malik Nov 16 '14 at 17:30
  • It says 'Unhandled exception type ParseException', and as it is your code that I'm trying to use, you are more experienced to help me than i am myself – user296950 Nov 16 '14 at 17:30
  • yes, you need to add a try catch block. If you're using a eclipse, there should be an option to let it fix it for you, im sure other IDE's have similar options too – Hamzah Malik Nov 16 '14 at 17:31
  • @HamzahMalik please read about threading, concurrency, timing and time events... it's all in the books already. If a event is time-dependent, you should return the control to OS while waiting for it, not put the CPU load to 100% just for the sake of it. –  Nov 16 '14 at 17:32
  • I've put in a try- catch block, with my do{int one = 1; System.out.println(one); one++; }, but it only outputs '1' then stops, even though the time has not yet elapsed – user296950 Nov 16 '14 at 17:34
  • Every loop, youre saying one = 1 . You need to put the int one=1 bit outside the loop – Hamzah Malik Nov 16 '14 at 17:35
  • If your using 12:00 as time it stops in the afternoon. If you'd like to run your program until you stop it, you could use `true` as condition of the while loop and abort exeuction with `CTRL+C` via command line. However as @vaxquis mentioned: Use a Thread.sleep() inside your loop to prevent your application from consuming all your CPU. – TobiasMende Nov 16 '14 at 17:37
  • I've put it outside, but still only 1 number, '1', is outputted on the screen. Even before, it should have just outputted a lot of 1s until the time has been reached? – user296950 Nov 16 '14 at 17:37
  • Has it got anything to do with the type of time? Can i use 17:40 instead of 5:40? – user296950 Nov 16 '14 at 17:38
  • Yes you can. The time is expected in 24:00 format. However your approach is not the best way to solve this kind of problem. See @vaxquis answer. – TobiasMende Nov 16 '14 at 17:39
  • see edited answer. I added date to the time to stop, otherwise itll stop at 12:00 1/1/1970, which has passed ages ago. Note that this solution will only work today, youd have to use logic to get the current day and use that as time to stop – Hamzah Malik Nov 16 '14 at 17:40
  • Argh still the same result. If you have time can you copy the code and try for yourself, to see if its just me? – user296950 Nov 16 '14 at 17:43