Example usage for com.google.common.util.concurrent AbstractScheduledService AbstractScheduledService

List of usage examples for com.google.common.util.concurrent AbstractScheduledService AbstractScheduledService

Introduction

In this page you can find the example usage for com.google.common.util.concurrent AbstractScheduledService AbstractScheduledService.

Prototype

protected AbstractScheduledService() 

Source Link

Document

Constructor for use by subclasses.

Usage

From source file:dk.dma.ais.view.AisViewDaemon.java

@Override
protected void runDaemon(Injector injector) throws Exception {
    // Tracking of live data
    final TargetTracker targetTracker = new TargetTracker();

    // A cache manager where caches can be held and retrieved
    final CacheManager cacheManager = new CacheManager();

    // Setup the readers
    AisReaderGroup g = AisReaders.createGroup("AisView",
            sources == null ? Collections.<String>emptyList() : sources);
    AisReaders.manageGroup(g);//from w  ww  .  j av  a  2  s .co  m

    // A job manager that takes care of tracking ongoing jobs
    final JobManager jobManager = new JobManager();

    // Setup the backup process
    // Files.createDirectories(backup);
    backup.mkdirs();
    if (!backup.isDirectory()) {
        throw new IOException("Unable to create directories for " + backup);
    }

    start(new TargetTrackerFileBackupService(targetTracker, backup.toPath()));

    // start tracking
    targetTracker.readFromStream(g.stream());

    //target tracking cleanup service
    start(new AbstractScheduledService() {

        @Override
        protected Scheduler scheduler() {
            return Scheduler.newFixedDelaySchedule(1, 10, TimeUnit.MINUTES);
        }

        @Override
        protected void runOneIteration() throws Exception {
            final Date satellite = new Date(new Date().getTime() - (1000 * 60 * 60 * 48));
            final Date live = new Date(new Date().getTime() - (1000 * 60 * 60 * 12));

            targetTracker.removeAll(new BiPredicate<AisPacketSource, TargetInfo>() {

                @Override
                public boolean test(AisPacketSource t, TargetInfo u) {
                    switch (t.getSourceType()) {
                    case SATELLITE:
                        return !u.hasPositionInfo() || new Date(u.getPositionTimestamp()).before(satellite);
                    default:
                        return !u.hasPositionInfo() || new Date(u.getPositionTimestamp()).before(live);
                    }

                }
            });

        }
    });

    //target cleanup missing static data
    start(new AbstractScheduledService() {

        @Override
        protected Scheduler scheduler() {
            return Scheduler.newFixedDelaySchedule(1, 24, TimeUnit.HOURS);
        }

        @Override
        protected void runOneIteration() throws Exception {

            targetTracker.removeAll(new BiPredicate<AisPacketSource, TargetInfo>() {
                @Override
                public boolean test(AisPacketSource t, TargetInfo u) {
                    return !u.hasStaticInfo();
                }
            });

        }
    });

    start(g.asService());

    // Start Ais Store Connection
    CassandraConnection con = null;
    if (!noCassandra && !cassandraSeeds.isEmpty()) {
        con = start(CassandraConnection.create("aisdata", cassandraSeeds));
        LOG.info("Connected to Cassandra cluster " + con.getSession().getCluster().getClusterName());
    } else {
        LOG.warn("Not connected to any cassandra cluster.");
    }

    WebServer ws = new WebServer(port);
    ws.getContext().setAttribute(AbstractResource.CONFIG,
            AbstractResource.create(g, con, targetTracker, cacheManager, jobManager));

    ws.start();
    LOG.info("AisView started");
    ws.join();
}

From source file:com.dssmp.agent.tailing.FileTailer.java

public FileTailer(AgentContext agentContext, FileFlow<R> flow, SourceFileTracker fileTracker,
        AsyncPublisherService<R> publisher, IParser<R> parser, FileCheckpointStore checkpoints)
        throws IOException {
    super();// www . ja  v  a 2 s  . c  o  m
    this.agentContext = agentContext;
    this.flow = flow;
    this.serviceName = super.serviceName() + "[" + this.flow.getId() + "]";
    this.checkpoints = checkpoints;
    this.publisher = publisher;
    this.parser = parser;
    this.fileTracker = new SourceFileTracker(this.agentContext, this.flow);
    this.minTimeBetweenFilePollsMillis = flow.minTimeBetweenFilePollsMillis();
    this.maxTimeBetweenFileTrackerRefreshMillis = flow.maxTimeBetweenFileTrackerRefreshMillis();
    this.metricsEmitter = new AbstractScheduledService() {
        @Override
        protected void runOneIteration() throws Exception {
            FileTailer.this.emitStatus();
        }

        @Override
        protected Scheduler scheduler() {
            return Scheduler.newFixedRateSchedule(
                    FileTailer.this.agentContext.logStatusReportingPeriodSeconds(),
                    FileTailer.this.agentContext.logStatusReportingPeriodSeconds(), TimeUnit.SECONDS);
        }

        @Override
        protected String serviceName() {
            return FileTailer.this.serviceName() + ".MetricsEmitter";
        }

        @Override
        protected void shutDown() throws Exception {
            LOGGER.debug("{}: shutting down...", serviceName());
            // Emit status one last time before shutdown
            FileTailer.this.emitStatus();
            super.shutDown();
        }
    };
}

From source file:com.amazon.kinesis.streaming.agent.Agent.java

public Agent(AgentContext agentContext) {
    this.logger = Logging.getLogger(Agent.class);
    this.agentContext = agentContext;
    this.sendingExecutor = getSendingExecutor(agentContext);
    this.checkpoints = new SQLiteFileCheckpointStore(agentContext);
    this.heartbeat = new HeartbeatService(this.agentContext, 1, TimeUnit.SECONDS) {
        @Override//from   w w w.jav a 2  s  .c  o  m
        protected Object heartbeat(AgentContext agent) {
            return Agent.this.heartbeat(agent);
        }

        @Override
        protected String serviceName() {
            return getClass().getSimpleName() + "[" + state().toString() + "]";
        }
    };
    this.metricsEmitter = new AbstractScheduledService() {
        @Override
        protected void runOneIteration() throws Exception {
            Agent.this.emitStatus();
        }

        @Override
        protected Scheduler scheduler() {
            return Scheduler.newFixedRateSchedule(Agent.this.agentContext.logStatusReportingPeriodSeconds(),
                    Agent.this.agentContext.logStatusReportingPeriodSeconds(), TimeUnit.SECONDS);
        }

        @Override
        protected String serviceName() {
            return Agent.this.serviceName() + ".MetricsEmitter";
        }

        @Override
        protected void shutDown() throws Exception {
            logger.debug("{}: shutting down...", serviceName());
            // Emit status one last time before shutdown
            Agent.this.emitStatus();
            super.shutDown();
        }
    };
    this.name = getClass().getSimpleName();
}

From source file:com.dopsun.msg4j.o2m.impl.O2mServerImpl.java

O2mServerImpl(Transport transport, O2mServerConfiguration config)
        throws TransportException, O2mServiceException {
    Objects.requireNonNull(transport);
    Objects.requireNonNull(config);

    Objects.requireNonNull(config.getServerId());
    Objects.requireNonNull(config.getSessionIdSupplier());

    Objects.requireNonNull(config.getHeartbeatInterval());

    Objects.requireNonNull(config.getSystemSubject());
    Objects.requireNonNull(config.getRequestSubject());
    Objects.requireNonNull(config.getPublishSubjectProducer());
    Objects.requireNonNull(config.getSessionSubjectProducer());

    Objects.requireNonNull(config.getRequestHandler());
    Objects.requireNonNull(config.getSnapshotProvider());

    this.transport = transport;
    this.serverId = config.getServerId();
    this.sessionId = config.getSessionIdSupplier().get();

    this.heartbeatInterval = config.getHeartbeatInterval();

    this.requestHandler = config.getRequestHandler();
    this.snapshotProvider = config.getSnapshotProvider();

    this.sessionSubjectProducer = config.getSessionSubjectProducer();
    this.publishSubjectProducer = config.getPublishSubjectProducer();
    this.systemTopic = transport.createTopic(config.getSystemSubject(), ProducerMode.NON_PERSISTENT,
            ConsumerMode.NO_ACK);/*from www .  j a v a 2s .  co  m*/

    this.systemPublisher = new ChannelSystemPublisher<>(sessionId, (msg) -> {
        try {
            transport.publish(systemTopic, msg);
        } catch (Exception e) {
            o2mServerEvents.onPublishSystemFailed(msg, e);
        }

        return /* Void */ null;
    });

    /** @formatter:off */
    ImmutableMap.Builder<String, ServerRequestHandler> builder = ImmutableMap.builder();

    builder.put(O2mMessages.Messages.CLIENT_CONNECT_REQUEST, new ServerClientConnectRequestHandler(this));
    builder.put(O2mMessages.Messages.CLIENT_DISCONNECT_REQUEST, new ServerClientDisconnectRequestHandler(this));
    builder.put(O2mMessages.Messages.USER_REQUEST, new ServerUserRequestHandler(this));
    builder.put(O2mMessages.Messages.SUBSCRIBE_REQUEST, new ServerSubscribeRequestHandler(this));

    systemRequestHandlers = builder.build();
    /** @formatter:on */

    TransportTopic requestTopic = transport.createTopic(config.getRequestSubject(), ProducerMode.NON_PERSISTENT,
            ConsumerMode.NO_ACK);
    TransportSubscriberSettings requestSettings = TransportSubscriberSettings.create();
    requestSubscription = transport.subscribe(requestTopic, requestSettings, this::onRequestMessage);

    comareAndSetState(O2mServerState.INITIALIZING, O2mServerState.STARTING);

    comareAndSetState(O2mServerState.STARTING, O2mServerState.ACTIVE);

    systemPublisher.sendServerStartedNotification(serverId, version);

    heartbeatPublishService = new AbstractScheduledService() {
        @Override
        protected Scheduler scheduler() {
            return Scheduler.newFixedRateSchedule(heartbeatInterval.toMillis(), heartbeatInterval.toMillis(),
                    TimeUnit.MILLISECONDS);
        }

        @Override
        protected void runOneIteration() throws Exception {
            long stamp = stateLock.readLock();
            try {
                if (state.get().equals(O2mServerState.ACTIVE)) {
                    ServerClientHeartbeatWriter writer = O2mMessages.newServerClientHeartbeat();

                    try {
                        systemPublisher.syncPublish(writer.getMessage());
                    } catch (Exception e) {
                        o2mServerEvents.onPublishHeartbeatFailed(e);
                    }
                }
            } finally {
                stateLock.unlockRead(stamp);
            }
        }
    };
    heartbeatPublishService.startAsync();
}