How to make every 0.5 seconds add 1 to a variable?

    2 answers 2

    The function that is called every 500ms and increases the counter variable by 1:

     new Timer().scheduleAtFixedRate(new TimerTask(){ @Override public void run(){ counter++; Log.i("tag", "A Kiss every 5 seconds"); } }, 0, 500); 

    Understandably, the counter variable must be defined in the accessible scope, for example, in the properties of the current class.

    • Doesn't the timer work in a separate thread? If yes, then there may be problems with a non-atomic increment. - Nick Volynkin
     for(;;) { TimeUnit.MILLISECONDS.sleep(500); counter++; }