RepeatingPublisher.java
Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2011 Google Inc.
00003  * 
00004  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
00005  * use this file except in compliance with the License. You may obtain a copy of
00006  * the License at
00007  * 
00008  * http://www.apache.org/licenses/LICENSE-2.0
00009  * 
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
00012  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
00013  * License for the specific language governing permissions and limitations under
00014  * the License.
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 }


rosjava_core
Author(s):
autogenerated on Wed Aug 26 2015 16:06:49