Question

Im trying to get a timer to work in my current java project that adds 1 to an integer variable every n microseconds (e.g. 500 for 1/2 a second), within an infinite loop, so that it is always running while the program runs. Heres the code i have currently:

public class Ticker
{
    public int time = 0;
    long t0, t1;

    public void tick(int[] args)
    {
        for (int i = 2; i < 1; i++)
        {
            t0 = System.currentTimeMillis();
            do
            {
                t1 = System.currentTimeMillis();
            }
            while (t1 - t0 < 500);
            time = time + 1;
        }
    }
}

Everyone was so helpful with my last question, hopefully this one is just as easy

Was it helpful?

Solution 2

Here is an comparable ScheduledExecutorService example which will update the time variable with a 500 millisecond interval:

ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);

exec.scheduleAtFixedRate(new Runnable(){
    private int time = 0;

    @Override
    public void run(){
        time++;
        System.out.println("Time: " + time);
    }
}, 0, 500, TimeUnit.MILLISECONDS);

This approach is preferred over using Timer.

OTHER TIPS

I think you want

Thread.sleep(500);

At the moment you're consuming CPU cycles waiting for 500ms (you mention microseconds but I believe you want milliseconds). The above puts your current thread to sleep for 500ms and your process won't consume any CPU (or minimal at least - garbage collection will still be running). If you watch the CPU when you run your version you should see the difference.

See here for more info.

If you need to do it in a different thread, take a look on Timer:

int delay = 500; //milliseconds
ActionListener taskPerformer = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        time++
    }
};
new Timer(delay, taskPerformer).start();

Note that the code above cannot utilize a local variable (they must be declared as final to access them in an anonymous class). It can be a member however.

What you have is rather inefficient, since it wastes CPU cycles waiting for the next wakeup time. If I were you, I'd rewrite the function using Thread.sleep().

As to why your current code doesn't work, your for loop conditions are off, so the loop is never entered.

To have the timer code run concurrently with whatever other logic you have in your program, you'll need to look into threading.

It sounds like you might want to look into multithreading. If you search SO for this, you will find several good question/answer threads. There are also tutorials elsewhere on the web...

Have a look at Timer or better ScheduledExecutorService. They enable you to execute some action periodically and handle the computations surrounding that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top