Search code examples
javatimerscheduled-tasksvert.x

Is there any way to set initial delay (i.e 30 sec) in Vertx and then run task periodically with different time delay (i.e 1 sec)


I am using vert.x framework to write a Java application. I have a use case where I need to wait for 30 seconds before scheduling task for 1 second interval.

I am using vertx.setPeriodic to execute task every 1 second. Here I am not able to find any utility of vertex which allows me to wait for 30 seconds initially before executing task every 1 second. I can use Thread.sleep(30000), but it will make my code synchronous. Rather I am looking for a vertx function which allow me to achieve same behavior asyc way.

vertx.setPeriodic(1000, timerId -> { ... my task logic ... });

I tried using vertx.setPeriodic, but it do not have overloaded method which allows initial delay.


Solution

  • This should be simple in combination with vertx.setTimer(long delay, Handler<Long> handler)

    Your code would look like this:

    vertx.setTimer(30000, timerId -> {
        vertx.setPeriodic(1000, periodicId -> { ... my task logic ... });
    });
    

    EDIT: in recent versions of Vert.x, setPeriodic initial delay can be configured:

    vertx.setPeriodic(30000, 1000, timerId -> {
     // My task
    });