Schedule an event in Vert.x using vertx-cron

The vertx-cron module allows you to schedule events based on a cron specification. Vertx has setTimer() and setPeriodic() to help you schedule future or repetitive tasks but they aren’t as useful when the scheduling requirement becomes complicated. Like if you wanted to run some task every minute from 9am to 5pm on weekdays.

The vertx-cron module make it easy. Just add the Maven dependency to your pom.

<dependency>
    <groupId>com.diabolicallabs</groupId>
    <artifactId>vertx-cron</artifactId>
    <version>3.2.1.1</version>
</dependency>

Now you can schedule an event by sending a JSON object like the following to the ‘cron.schedule’ address.

{
    "cron_expression": "0 0 16 1/1 * ? *",
    "time_zone": "US/Hawaii"
    "address": "stock.quotes.list",
    "message": {
        "ticker": "RHT"
    },
    "action": "send",
    "result_address": "stock.quotes.persist"
}

This will send the message {“ticker”:”RHT”} to the “stock.quotes.list” consumer every day at 4pm in the Hawaii timezone. When “stock.quotes.list” responds, the response will be forwarded to “stock.quotes.persist”

It may be important to specify the timezone if you intend to have a Vert.x cluster with nodes in various parts of the world. This will ensure that the events fire at the same time no matter where the vertical is deployed.

There is also an RxJava Observer that makes it even easier. If you are using Vert.x Rx you can make use of the CronObservable class like the following.

Scheduler scheduler = RxHelper.scheduler(vertx);
CronObservable.cronspec(scheduler, "0 0 16 1/1 * ? *", "US/Eastern")
  .take(5) //If you only want it to hit 5 times, add this, remove for continuous emission
  .subscribe(
    timestamped -> {
      //Perform the scheduled activity here
    },
    fault -> {
      //If there is some kind of fault, handle here
    }
  );

First you need a Vert.x scheduler from the RxHelper. Then call the static method cronspec with the scheduler, the cron specification and an option timezone. That will return an Observable over a Timestamp. You can then use the Observable in any way you normally would.

Once you subscribe, a timestamp will be emitted each time the cron schedule hits, in the case every day at 4pm in the US Eastern timezone.

Leave a Reply

Your email address will not be published. Required fields are marked *