Search code examples
javacounterticker

(Java) Ticker that adds to counter variable


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


Solution

  • 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.