John Arckai
John Arckai

Reputation: 93

How to run a method in Java using a timer?

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);
}

Upvotes: 0

Views: 113

Answers (5)

user637357
user637357

Reputation: 1

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);

    }
}

Upvotes: 0

Michele Mariotti
Michele Mariotti

Reputation: 7469

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");
    }
}

Upvotes: 0

Ioan
Ioan

Reputation: 5187

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.

Upvotes: 1

Sachin
Sachin

Reputation: 3554

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);
    }

Upvotes: 1

Dropout
Dropout

Reputation: 13866

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()

Upvotes: 0

Related Questions