Scheduling tasks with Eclipse Vert.x

cescoffier
238 views

Open Source Your Knowledge, Become a Contributor

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

Create Content

Periodic Timers

Vert.x also supports scheduling periodic tasks. The timer fires periodically calling the handler every time. There will be an initial delay equal to the period.

Periodic timer
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;
public class PeriodicExample {
private static int counter = 0;
public static void main(String... args) {
Vertx vertx = Vertx.vertx();
long timerId = vertx.setPeriodic(1000, id -> {
System.out.println("Hello " + ++counter);
});
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

The return value of setPeriodic is a unique timer id (long). This can be later used if the timer needs to be cancelled. The argument passed into the timer event handler is also the unique timer id. So, the action can decide to cancel the periodic task.

Keep in mind that the timer will fire on a periodic basis. If your periodic treatment takes a long amount of time to proceed, your timer events could run continuously or even worse : stack up. In this case, you should consider using setTimer instead. Once your treatment has finished, you can set the next timer:

    private static Handler<Long> action;

    public static void main(String... args) {
        Vertx vertx = Vertx.vertx();

        action = id -> {
            // Execute the task
            // ...

            // Schedule the next execution in one hour
            vertx.setTimer(TimeUnit.HOURS.toMillis(1), action);
        };

        // Schedule the first execution
        vertx.setTimer(TimeUnit.HOURS.toMillis(1), action);
    }
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content