Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

timer

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.

like image 874
23k Avatar asked Dec 20 '22 01:12

23k


1 Answers

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.

like image 63
ash Avatar answered May 19 '23 14:05

ash