23k
23k

Reputation: 1399

Printing something in Java after a certain amount of time has passed

I'm working on a text adventure game for my Java class, and I'm running into a problem while trying to time a print statement from showing up in the console.

Basically after 45 seconds I would like a print statement to show up, in this case the print statement would be reminding the user that they need to let their virtual dog out...

I also need the timer to reset after the user gives the correct command.

Upvotes: 4

Views: 14436

Answers (5)

ash
ash

Reputation: 5155

import java.util.Timer;
import java.util.TimerTask;

...

Timer timer = new Timer();
timer.schedule(new TimerTask() { 
   @Override  
   public void run() {
       System.out.println("delayed hello world");
   }
},  45000);

Timer

TimerTask

To cancel the timer, either use a TimerTask variable to remember the task and then call its cancel() method, or use timer.purge(); the latter cancels all tasks on the timer. To schedule the task again, just repeat.

You'll probably want to do more advanced operations in the future, so reading the Timer API docs is a good idea.

Upvotes: 8

0decimal0
0decimal0

Reputation: 3984

 Timer timer = new Timer();
 timer.schedule(new TimerTask(){
    public void run() {
       System.out.println(" let the virtual dog out ");
    }
  }, 45000);

Upvotes: 2

Sri Harsha Chilakapati
Sri Harsha Chilakapati

Reputation: 11940

Try running in a new Thread.

new Thread(new Runnable()
{
    public void run()
    {
        Thread.sleep(45000);
        System.out.println("My message");
    }
})
.run();

This should work.

Upvotes: 1

Ali
Ali

Reputation: 949

Tell the main thread to sleep might not be ideal as it will cause your program to basically stop. Use a another thread(need to do a little multi-threading) for timing your output and do a check if the message should be printed after the 45s.

Upvotes: 0

ozborn
ozborn

Reputation: 1070

Just tell the thread to sleep for 45 seconds, there is a tutorial here:

http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html

Upvotes: 0

Related Questions