Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017 package org.ros.internal.node.topic;
00018
00019 import com.google.common.base.Preconditions;
00020
00021 import org.apache.commons.logging.Log;
00022 import org.apache.commons.logging.LogFactory;
00023 import org.ros.concurrent.CancellableLoop;
00024 import org.ros.node.topic.Publisher;
00025
00026 import java.util.concurrent.ScheduledExecutorService;
00027
00033 public class RepeatingPublisher<MessageType> {
00034
00035 private static final boolean DEBUG = false;
00036 private static final Log log = LogFactory.getLog(RepeatingPublisher.class);
00037
00038 private final Publisher<MessageType> publisher;
00039 private final MessageType message;
00040 private final int frequency;
00041 private final RepeatingPublisherLoop runnable;
00042
00046 private final ScheduledExecutorService executorService;
00047
00048 private final class RepeatingPublisherLoop extends CancellableLoop {
00049 @Override
00050 public void loop() throws InterruptedException {
00051 publisher.publish(message);
00052 if (DEBUG) {
00053 log.info(String.format("Published message %s to publisher %s ", message, publisher));
00054 }
00055 Thread.sleep((long) (1000.0d / frequency));
00056 }
00057 }
00058
00065 public RepeatingPublisher(Publisher<MessageType> publisher, MessageType message, int frequency,
00066 ScheduledExecutorService executorService) {
00067 this.publisher = publisher;
00068 this.message = message;
00069 this.frequency = frequency;
00070 this.executorService = executorService;
00071 runnable = new RepeatingPublisherLoop();
00072 }
00073
00074 public void start() {
00075 Preconditions.checkState(!runnable.isRunning());
00076 executorService.execute(runnable);
00077 }
00078
00079 public void cancel() {
00080 Preconditions.checkState(runnable.isRunning());
00081 runnable.cancel();
00082 }
00083 }