0

How would I have this method run every couple of seconds in a recursive function. I want the i variable to update by 1 every couple of seconds than print it to the console. In javascript I could use setTimeout is there a method like the javascript setTimeout in Java?

final i = 0;
public void timerActions() {
     i = i + 1;
     System.out.println(i);
}
1
  • you can use Thread.sleep(1000); if this is just for fun. Commented Dec 19, 2013 at 8:23

5 Answers 5

1

try with Timer

Timer timer = new Timer("Display Timer");

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                timerActions();
            }
        };
        // This will invoke the timer every second
        timer.scheduleAtFixedRate(task, 1000, 1000);
    }
Sign up to request clarification or add additional context in comments.

Comments

1

You should use ScheduledExecutorService for that.

Update per Peter Lawrey comment (thanks):

Methods :

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                              long initialDelay,
                                              long period,
                                              TimeUnit unit);

and

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                 long initialDelay,
                                                 long delay,
                                                 TimeUnit unit);

can be used in order to achieve your desired behavior.

1 Comment

schedule only does it once.
0

You can put the Thread to sleep after execution if it's just a simple application which just has to "run slower".

For example:

final i = 0;
public void timerActions() {
    i++;
    System.out.println(i);
    Thread.sleep(1000);
}

1000 in the parentheses means 1000ms=1second - the amount of time in which the thread sleeps. This is a simple way to do it, but be aware that in larger multi-threaded applications you have to take into acount thread safety and related problems.

Documentation for Thread.sleep()

Comments

0
public class TimedAction
{
    public static void main(String[] args) throws Exception
    {
        System.out.println("begin");

        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        Runnable command = new Runnable()
        {
            private int i = 0;

            @Override
            public void run()
            {
                // put your logic HERE
                System.out.println(i++);
            }
        };

        // execute command, immediately (0 delay), and every 2 seconds
        executor.scheduleAtFixedRate(command, 0, 2, TimeUnit.SECONDS);

        System.in.read();

        executor.shutdownNow();
        executor.awaitTermination(5, TimeUnit.SECONDS);

        System.out.println("end");
    }
}

Comments

0

This will print "Counting..." on every 2 seconds

import java.util.Timer;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask {

private int counter = 0;

public void run() {
    counter++;
    if (counter <= 3) {
        System.out.println("Counting - counter = " + counter);
    } else {
        System.out.println("Stopping timer execution");
        this.cancel();
    }
}


public static void main(String[] args) {

    Timer timer = new Timer("TimerThreadName");
    MyTimerTask task = new MyTimerTask();

    // void java.util.Timer.schedule(TimerTask task, long delay, long period)
    timer.schedule(task, 0, 2000);

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.