Scheduling tasks with Eclipse Vert.x

cescoffier
236 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

One-shot Timers

The first type of timer is used to create a delayed action. An one-shot timer calls a handler after a certain delay, expressed in milliseconds. A Handler being a method invoked by Vert.x when something interesting happen - here the execution trigger.

One-shot timer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package io.vertx.playground;
import io.vertx.core.Vertx;
public class TimerExample {
public static void main(String... args) {
Vertx vertx = Vertx.vertx();
System.out.println("Starting, waiting for greetings");
vertx.setTimer(5000, l -> {
System.out.println("Hello");
});
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

The return value is a unique timer id which can later be used to cancel the timer. The handler is also passed the timer id.

Passing milliseconds can be inconvenient for long durations. Fortunately, you can use TimeUnit:

Using TimeUnit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package io.vertx.playground;
import io.vertx.core.Vertx;
import java.util.concurrent.TimeUnit;
public class TimerWithDurationExample {
public static void main(String... args) {
Vertx vertx = Vertx.vertx();
System.out.println("Starting, waiting for greetings");
vertx.setTimer(TimeUnit.SECONDS.toMillis(5), l -> {
System.out.println("Hello");
});
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

To give another example, you can compute the number of milliseconds in a hour using:

TimeUnit.HOURS.toMillis(1)
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content