Example usage for io.vertx.core Vertx setTimer

List of usage examples for io.vertx.core Vertx setTimer

Introduction

In this page you can find the example usage for io.vertx.core Vertx setTimer.

Prototype

long setTimer(long delay, Handler<Long> handler);

Source Link

Document

Set a one-shot timer to fire after delay milliseconds, at which point handler will be called with the id of the timer.

Usage

From source file:examples.CoreExamples.java

License:Open Source License

public void example15(Vertx vertx) {
    long timerID = vertx.setTimer(1000, id -> {
        System.out.println("And one second later this is printed");
    });/* w  w  w.  j  a  v  a2 s  .co m*/

    System.out.println("First this is printed");
}

From source file:examples.SharedDataExamples.java

License:Open Source License

public void example5(Vertx vertx, SharedData sd) {
    sd.getLock("mylock", res -> {
        if (res.succeeded()) {
            // Got the lock!
            Lock lock = res.result();

            // 5 seconds later we release the lock so someone else can get it

            vertx.setTimer(5000, tid -> lock.release());

        } else {/*from   w ww. j  a va2s.  co m*/
            // Something went wrong
        }
    });
}

From source file:examples.ShellExamples.java

License:Open Source License

public void asyncCommand(CommandBuilder command) {
    command.processHandler(process -> {
        Vertx vertx = process.vertx();

        // Set a timer
        vertx.setTimer(1000, id -> {

            // End the command when the timer is fired
            process.end();//  w  ww .  j a  va2 s. com
        });
    });
}

From source file:examples.VertxKafkaClientExamples.java

License:Apache License

/**
 * Example about how Kafka consumer can pause reading from a topic partition
 * and then resume read operation for continuing to get messages
 * @param vertx/*from   ww  w  .ja  va 2s  . co  m*/
 * @param consumer
 */
public void exampleConsumerFlowControl(Vertx vertx, KafkaConsumer<String, String> consumer) {

    TopicPartition topicPartition = new TopicPartition().setTopic("test").setPartition(0);

    // registering the handler for incoming messages
    consumer.handler(record -> {
        System.out.println("key=" + record.key() + ",value=" + record.value() + ",partition="
                + record.partition() + ",offset=" + record.offset());

        // i.e. pause/resume on partition 0, after reading message up to offset 5
        if ((record.partition() == 0) && (record.offset() == 5)) {

            // pause the read operations
            consumer.pause(topicPartition, ar -> {

                if (ar.succeeded()) {

                    System.out.println("Paused");

                    // resume read operation after a specific time
                    vertx.setTimer(5000, timeId -> {

                        // resumi read operations
                        consumer.resume(topicPartition);
                    });
                }
            });
        }
    });
}

From source file:net.ssorj.quiver.QuiverArrowVertxProton.java

License:Apache License

private static void doMain(final String[] args) throws Exception {
    final HashMap<String, String> kwargs = new HashMap<>();

    for (String arg : args) {
        final String[] elems = arg.split("=", 2);
        kwargs.put(elems[0], elems[1]);// w  w  w  .ja v  a  2s.  c o  m
    }

    final String connectionMode = kwargs.get("connection-mode");
    final String channelMode = kwargs.get("channel-mode");
    final String operation = kwargs.get("operation");
    final String id = kwargs.get("id");
    final String host = kwargs.get("host");
    final int port = Integer.parseInt(kwargs.get("port"));
    final String path = kwargs.get("path");
    final int desiredDuration = Integer.parseInt(kwargs.get("duration"));
    final int desiredCount = Integer.parseInt(kwargs.get("count"));
    final int bodySize = Integer.parseInt(kwargs.get("body-size"));
    final int creditWindow = Integer.parseInt(kwargs.get("credit-window"));
    final int transactionSize = Integer.parseInt(kwargs.get("transaction-size"));
    final boolean durable = Integer.parseInt(kwargs.get("durable")) == 1;

    if (!CLIENT.equalsIgnoreCase(connectionMode)) {
        throw new RuntimeException("This impl currently supports client mode only");
    }

    if (!ACTIVE.equalsIgnoreCase(channelMode)) {
        throw new RuntimeException("This impl currently supports active mode only");
    }

    if (transactionSize > 0) {
        throw new RuntimeException("This impl doesn't support transactions");
    }

    final boolean sender;

    if (SEND.equalsIgnoreCase(operation)) {
        sender = true;
    } else if (RECEIVE.equalsIgnoreCase(operation)) {
        sender = false;
    } else {
        throw new java.lang.IllegalStateException("Unknown operation: " + operation);
    }

    final CountDownLatch completionLatch = new CountDownLatch(1);
    final Vertx vertx = Vertx.vertx(new VertxOptions().setPreferNativeTransport(true));
    final ProtonClient client = ProtonClient.create(vertx);

    client.connect(host, port, (res) -> {
        if (res.succeeded()) {
            final ProtonConnection connection = res.result();

            connection.setContainer(id);
            connection.closeHandler(x -> {
                completionLatch.countDown();
            });

            if (desiredDuration > 0) {
                vertx.setTimer(desiredDuration * 1000, timerId -> {
                    connection.close();
                });
            }

            if (sender) {
                send(connection, path, desiredCount, bodySize, durable);
            } else {
                receive(connection, path, desiredCount, creditWindow);
            }
        } else {
            res.cause().printStackTrace();
            completionLatch.countDown();
        }
    });

    // Await the operations completing, then shut down the Vertx
    // instance.
    completionLatch.await();

    vertx.close();
}

From source file:org.apache.servicecomb.faultinjection.DelayFault.java

License:Apache License

private void executeDelay(FaultParam faultParam, AsyncResponse asynResponse, long delay) {
    Vertx vertx = faultParam.getVertx();
    if (vertx != null) {
        vertx.setTimer(delay, timeID -> asynResponse.success(SUCCESS_RESPONSE));
        return;//  w w  w  .  jav  a2  s .  c o m
    }

    try {
        Thread.sleep(delay);
    } catch (InterruptedException e) {
        LOGGER.info("Interrupted exception is received");
    }
    asynResponse.success(SUCCESS_RESPONSE);
}

From source file:org.jberet.vertx.rest.JBeretRouterConfig.java

License:Open Source License

private static void scheduleJob(final RoutingContext routingContext) {
    final String jobXmlName = routingContext.pathParam("jobXmlName");
    final HttpServerRequest request = routingContext.request();
    final String delayString = request.getParam("delay");
    final long delay = delayString == null ? DEFAULT_SCHEDULE_DELAY : Long.parseLong(delayString);
    final String periodicString = request.getParam("periodic");
    final boolean periodic = periodicString != null && Boolean.parseBoolean(periodicString);

    final Properties jobParams = getJobParameters(routingContext);
    final JobSchedule jobSchedule = new JobSchedule();
    jobSchedule.setDelay(delay);// w  w w.jav  a  2  s. com
    jobSchedule.setJobName(jobXmlName);
    jobSchedule.setJobParameters(jobParams);

    final long delayMillis = delay * 60 * 1000;
    final long timerId;
    final Vertx vertx = routingContext.vertx();
    if (!periodic) {
        timerId = vertx.setTimer(delayMillis, timerId1 -> {
            final JobExecutionEntity jobExecutionEntity = JobService.getInstance().start(jobXmlName, jobParams);
            setJobExecutionEntityHref(routingContext, jobExecutionEntity);
            jobSchedule.addJobExecutionIds(jobExecutionEntity.getExecutionId());
            jobSchedule.setStatus(JobSchedule.Status.DONE);
        });
    } else {
        timerId = vertx.setPeriodic(delayMillis, timerId1 -> {
            final JobExecutionEntity jobExecutionEntity = JobService.getInstance().start(jobXmlName, jobParams);
            setJobExecutionEntityHref(routingContext, jobExecutionEntity);
            jobSchedule.addJobExecutionIds(jobExecutionEntity.getExecutionId());

            //                 since this is periodic timer, there may be more in the future
            //                jobSchedule.setStatus(JobSchedule.Status.DONE);
        });
    }
    jobSchedule.setId(timerId);
    final LocalMap<String, JobSchedule> timerLocalMap = getTimerLocalMap(vertx);
    timerLocalMap.put(String.valueOf(timerId), jobSchedule);
    final JsonObject jsonObject = JsonObject.mapFrom(jobSchedule);
    sendJsonResponse(routingContext, jsonObject.encodePrettily());
}