Reputation: 250
Currently my project has no timing and is satisfactory but it would be a lot cleaner if I had timing. I would like to have it so after I declared whatever needs to be I can do something like:
if (timer == 2000) {
System.out.println("2 seconds have passed since "timer" was declared!");
}
I haven't seen that much that went over this. Sorry if I'm missing something. I'm just looking for the best way to do this.
EDIT
I've been asked for more detail on why I need this so... btw this is for a zombie game
while(!Display.isCloseRequested()){
if (whatever == 2 seconds){ //I obviously know a don't right the word seconds next the number 2
for(int z = 0; z < 2; z++){
SpawnaZombieAt(leftcorner,20,speed);
}
}
}
if I'm not clear enough I am trying to start some sort of timer. then for every 2 seconds or so 2 more zombies will spawn
Upvotes: 1
Views: 178
Reputation: 328873
If you want to launch a specific action after a specific delay, you can use a ScheduledExecutorService
- for example:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(new Runnable() {
public void run() {
System.out.println("2 seconds have passed since this action was scheduled!");
}
}, 2, TimeUnit.SECONDS);
And it will print your sentence after 2 seconds.
If you are after a stopwatch, the answers to this question propose several alternatives.
EDIT
Following your edit, the ScheduledExecutorService
has a scheduleAtFixedRate
method that would enable you to run a specific action every 2 seconds for example.
Upvotes: 1
Reputation: 269857
Are you looking for System.currentTimeMillis()
or System.nanoTime()
? The first is a low precision counter that corresponds to UTC, while the latter is a high precision timer that can be used to determine elapsed time.
Upvotes: 2