Skip to content
Lautaro Brasseur edited this page Jun 29, 2018 · 1 revision

Timer

Timer provides a platform agnostic way to schedule tasks.

As usual, you typically will inject it:

public class TimerExample {
    private final Timer timer;

    @Inject
    public TimerExample(Timer timer) {
        this.timer = checkNotNull(timer);
    }

    public void scheduleTask() {
        // This will write "Hi!!!" on the console after 1 second
        timer.schedule(() -> System.out.println("Hi!!!"),
                1000);
    }

    public void scheduleRepeatingTask() {
        // This will write "Hi!!!" on the console each 1 second
        timer.scheduleRepeating(() -> System.out.println("Hi!!!"),
                1000);
    }
}

Canceling task

You can cancel the returned task:

Timer.Task task = timer.schedule(() -> System.out.println("Hi!!!"),
        1000);
task.cancel();

Clone this wiki locally