Lucas Baizer
Lucas Baizer

Reputation: 325

Timer in Java that doesn't pause the program?

I was wondering if there was a form of timer that I can use that doesn't pause all of my code Thread.sleep(ms) is not what I need because it pauses all of my code.

EDIT: Okay, I think I misworded that. Here's my edit: Is there a way to measure a certain amount of time in Java without pausing my main method?

Upvotes: 0

Views: 105

Answers (3)

pasghetti
pasghetti

Reputation: 57

You might want to look into the Timer class. You can attach it to a thread, schedule events, and add delays. What you could do with this is you could create a thread to run along side your main thread and have it run from there. Because they will be on two completely different threads, you don't need to worry about them interfering with each other. To run the other thread, you could create a class that extends Thread and run it. Then use the Timer(String name) constructor to create a Timer for the thread.

Upvotes: 0

Bruno Volpato
Bruno Volpato

Reputation: 1428

I like to using Executors class. It have a nice method that is newScheduledThreadPool. It gives you an ScheduledExecutorService instance, which have a lot of scheduling methods.

Check it out here here: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(threadToExecute, 10, TimeUnit.SECONDS);

This code will start threadToExecute thread after 10 seconds, without pausing your main thread.

Upvotes: 1

Florian Schaetz
Florian Schaetz

Reputation: 10662

Depends on which Frameworks you use. A pretty generic way would be to start a new Thread, pause that Thread via Thread.sleep(ms) and then do whatever you want to do after that delay, but of course that requires a little bit of care because of concurrency issues.

Upvotes: 0

Related Questions