Vert.x Timers
Jakob Jenkov |
Vert.x has two types of timers which can be used to time the execution of code. The first timer type is a one-time timer which fires an event after a certain amount of time has passed. The second timer is a period timer which keeps firing events whenever an interval of the specified period has elapsed. This tutorial will cover both types of Vert.x timers in the following sections.
One-time Timers
A Vert.x one-time timer is a timer that fires a single time after a specified delay. Here is how you create a one-time timer:
long timerID = vertx.setTimer(3000, new Handler<Long>() { @Override public void handle(Long aLong) { System.out.println("Timer fired"); } });
The setTimer()
method takes a time interval in milliseconds as first parameter, and a
Handler
implementation as second parameter. The Handler
's handle()
method
is called when the time interval has elapsed.
The setTimer()
method returns a timer ID. This timer ID is also passed as parameter to the
Handler
's handle()
method. This timer ID is also used if you want to cancel the
timer later.
Periodic Timers
A Vert.x periodic timer is a timer that fires every time a specified period of time has passed. Here is how you create a periodic timer:
long timerID = vertx.setPeriodic(3000, new Handler<Long>() { @Override public void handle(Long aLong) { System.out.println("Timer 1 fired: " + aLong); } });
The setPeriodic()
method takes a time interval in milliseconds as first parameter, and a
Handler
implementation as second parameter. The Handler
's handle()
method
is called every time the time interval has elapsed.
The setPeriodic()
returns a timer ID. This timer ID is also passed to the Handler
's
handle()
method whenever it is called. The timer ID is also used if you want to cancel the timer
later.
Canceling a Timer
You can cancel a one-time or periodic timer using the cancelTimer()
method of the Vertx
object. The cancel()
method can cancel both one-time and periodic timers.
Here is an example of canceling a Vertx timer:
vertx.cancelTimer(timerID);
Tweet | |
Jakob Jenkov |