Example usage for java.util.concurrent Executors newSingleThreadScheduledExecutor

List of usage examples for java.util.concurrent Executors newSingleThreadScheduledExecutor

Introduction

In this page you can find the example usage for java.util.concurrent Executors newSingleThreadScheduledExecutor.

Prototype

public static ScheduledExecutorService newSingleThreadScheduledExecutor() 

Source Link

Document

Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically.

Usage

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

/**
 * There should be one DatabaseInfo object per agileBase application
 * instance. This constructor generates it. It bootstraps the application.
 * All schema objects are loaded into memory from the pervasive store.
 * /*ww  w. java 2 s . c  om*/
 * The authentication manager (AuthManagerInfo), store of all users, roles
 * and permissions is loaded too.
 * 
 * Finally, the data manager (a DataManagementInfo object) is created and
 * initialised
 * 
 * @throws CantDoThatException
 *             If more than one Authenticator was found in the database
 */
public DatabaseDefn(DataSource relationalDataSource, String webAppRoot) throws SQLException,
        ObjectNotFoundException, CantDoThatException, MissingParametersException, CodingErrorException {
    this.relationalDataSource = relationalDataSource;
    // Load table schema objects
    Session hibernateSession = HibernateUtil.currentSession();
    try {
        this.authManager = new AuthManager(relationalDataSource);
    } finally {
        HibernateUtil.closeSession();
    }
    // Methods and objects dealing with data as opposed to the schema are
    // kept in DataManagement
    this.dataManagement = new DataManagement(relationalDataSource, webAppRoot, this.authManager);
    DashboardPopulator dashboardPopulator = new DashboardPopulator(this);
    // Start first dashboard population immediately
    this.initialDashboardPopulatorThread = new Thread(dashboardPopulator);
    this.initialDashboardPopulatorThread.start();
    // and schedule regular dashboard population once a day at a time of low
    // activity
    int hourNow = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    int initialDelay = 24 + AppProperties.lowActivityHour - hourNow;
    this.dashboardScheduler = Executors.newSingleThreadScheduledExecutor();
    this.scheduledDashboardPopulate = dashboardScheduler.scheduleAtFixedRate(dashboardPopulator, initialDelay,
            24, TimeUnit.HOURS);
    // one-off boot actions
    // this.addCommentsFeedFields();
}

From source file:com.opengamma.integration.marketdata.WatchListRecorder.java

private static WatchListRecorder create(final URI serverUri, final String viewProcessorClassifier,
        final String securitySourceClassifier) {
    final RemoteComponentServer remote = new RemoteComponentServer(serverUri);
    final ComponentServer server = remote.getComponentServer();
    final ComponentInfo viewProcessorInfo = server.getComponentInfo(ViewProcessor.class,
            viewProcessorClassifier);/*from www.  ja v a 2s .  c  om*/
    final ComponentInfo securitySourceInfo = server.getComponentInfo(SecuritySource.class,
            securitySourceClassifier);

    final URI uri = URI.create(viewProcessorInfo.getAttribute(ComponentInfoAttributes.JMS_BROKER_URI));
    final ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(uri);
    final JmsConnectorFactoryBean factory = new JmsConnectorFactoryBean();
    factory.setName("WatchListRecorder");
    factory.setConnectionFactory(cf);
    factory.setClientBrokerUri(uri);
    final JmsConnector jmsConnector = factory.getObjectCreating();

    final ViewProcessor viewProcessor = new RemoteViewProcessor(viewProcessorInfo.getUri(), jmsConnector,
            Executors.newSingleThreadScheduledExecutor());
    // TODO: Not ideal; the published resolver should be used rather than an ad-hoc one created based just on the security source
    final ComputationTargetResolver targetResolver = new DefaultComputationTargetResolver(
            new RemoteSecuritySource(securitySourceInfo.getUri()));
    return new WatchListRecorder(viewProcessor, targetResolver);
}

From source file:org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent.java

@SuppressWarnings("unused")
protected void activate(ComponentContext componentContext) {
    try {//ww  w .j av a  2s. c  o  m
        if (log.isDebugEnabled()) {
            log.debug("Initializing device management core bundle");
        }
        /* Initializing Device Management Configuration */
        DeviceConfigurationManager.getInstance().initConfig();
        DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();

        DataSourceConfig dsConfig = config.getDeviceManagementConfigRepository().getDataSourceConfig();

        DeviceManagementDAOFactory.init(dsConfig);
        GroupManagementDAOFactory.init(dsConfig);
        NotificationManagementDAOFactory.init(dsConfig);
        OperationManagementDAOFactory.init(dsConfig);
        /*Initialize the device cache*/
        DeviceManagerUtil.initializeDeviceCache();

        /* Initialize Operation Manager */
        this.initOperationsManager();

        PushNotificationProviderRepository pushNotificationRepo = new PushNotificationProviderRepository();
        List<String> pushNotificationProviders = config.getPushNotificationConfiguration()
                .getPushNotificationProviders();
        if (pushNotificationProviders != null) {
            for (String pushNoteProvider : pushNotificationProviders) {
                pushNotificationRepo.addProvider(pushNoteProvider);
            }
        }
        DeviceManagementDataHolder.getInstance().setPushNotificationProviderRepository(pushNotificationRepo);

        /* If -Dsetup option enabled then create device management database schema */
        String setupOption = System.getProperty(DeviceManagementConstants.Common.SETUP_PROPERTY);
        if (setupOption != null) {
            if (log.isDebugEnabled()) {
                log.debug("-Dsetup is enabled. Device management repository schema initialization is about to "
                        + "begin");
            }
            this.setupDeviceManagementSchema(dsConfig);
        }

        /* Registering declarative service instances exposed by DeviceManagementServiceComponent */
        this.registerServices(componentContext);

        /* This is a workaround to initialize all Device Management Service Providers after the initialization
         * of Device Management Service component in order to avoid bundle start up order related complications */
        notifyStartupListeners();
        if (log.isDebugEnabled()) {
            log.debug("Push notification batch enabled : "
                    + config.getPushNotificationConfiguration().isSchedulerTaskEnabled());
        }
        // Start Push Notification Scheduler Task
        if (config.getPushNotificationConfiguration().isSchedulerTaskEnabled()) {
            if (config.getPushNotificationConfiguration().getSchedulerBatchSize() <= 0) {
                log.error("Push notification batch size cannot be 0 or less than 0. Setting default batch size "
                        + "to:" + DeviceManagementConstants.PushNotifications.DEFAULT_BATCH_SIZE);
                config.getPushNotificationConfiguration()
                        .setSchedulerBatchSize(DeviceManagementConstants.PushNotifications.DEFAULT_BATCH_SIZE);
            }
            if (config.getPushNotificationConfiguration().getSchedulerBatchDelayMills() <= 0) {
                log.error(
                        "Push notification batch delay cannot be 0 or less than 0. Setting default batch delay "
                                + "milliseconds to"
                                + DeviceManagementConstants.PushNotifications.DEFAULT_BATCH_DELAY_MILLS);
                config.getPushNotificationConfiguration().setSchedulerBatchDelayMills(
                        DeviceManagementConstants.PushNotifications.DEFAULT_BATCH_DELAY_MILLS);
            }
            if (config.getPushNotificationConfiguration().getSchedulerTaskInitialDelay() < 0) {
                log.error("Push notification initial delay cannot be less than 0. Setting default initial "
                        + "delay milliseconds to"
                        + DeviceManagementConstants.PushNotifications.DEFAULT_SCHEDULER_TASK_INITIAL_DELAY);
                config.getPushNotificationConfiguration().setSchedulerTaskInitialDelay(
                        DeviceManagementConstants.PushNotifications.DEFAULT_SCHEDULER_TASK_INITIAL_DELAY);
            }
            ScheduledExecutorService pushNotificationExecutor = Executors.newSingleThreadScheduledExecutor();
            pushNotificationExecutor.scheduleWithFixedDelay(new PushNotificationSchedulerTask(),
                    config.getPushNotificationConfiguration().getSchedulerTaskInitialDelay(),
                    config.getPushNotificationConfiguration().getSchedulerBatchDelayMills(),
                    TimeUnit.MILLISECONDS);
        }

        PrivacyComplianceProvider privacyComplianceProvider = new PrivacyComplianceProviderImpl();
        DeviceManagementDataHolder.getInstance().setPrivacyComplianceProvider(privacyComplianceProvider);
        componentContext.getBundleContext().registerService(PrivacyComplianceProvider.class.getName(),
                privacyComplianceProvider, null);

        if (log.isDebugEnabled()) {
            log.debug("Device management core bundle has been successfully initialized");
        }
    } catch (Throwable e) {
        log.error("Error occurred while initializing device management core bundle", e);
    }
}

From source file:com.web.server.EARDeployer.java

public void run() {
    StandardFileSystemManager fsManager = null;
    fsManager = new StandardFileSystemManager();
    try {/*from w  ww .ja  v a  2 s.c  om*/
        System.setProperty("java.io.tmpdir", this.cacheDir);
        /*DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir));
        //fsManager.setReplicator(new PrivilegedFileReplicator(replicator));
        fsManager.setTemporaryFileStore(replicator);*/
        fsManager.init();
    } catch (FileSystemException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
    }
    // fsManager.addProvider("file", new JarFileProvider());
    File file = new File(scanDirectory);
    File[] files = file.listFiles();
    CopyOnWriteArrayList<String> classList;
    ConcurrentHashMap jarClassListMap = new ConcurrentHashMap();
    task = new EARFileListener(executorServiceMap, urlClassLoaderMap, earsDeployed);
    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory())
            continue;
        // Long lastModified=(Long) fileMap.get(files[i].getName());
        if (files[i].getName().endsWith(".ear")) {
            String filePath = files[i].getAbsolutePath();
            com.web.server.util.FileUtil util = new com.web.server.util.FileUtil();
            FileObject earFile = null;
            try {
                System.out.println("Before resolve file");
                System.out.println("jar:file:///" + filePath);
                earFile = fsManager.resolveFile("jar:file:///" + scanDirectory + "/" + files[i].getName());
                System.out.println("After resolve file");
            } catch (FileSystemException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                deleteExecutorServicesEar(files[i].getName(), fsManager);
                deployExecutorServicesEar(files[i].getName(), earFile, fsManager);
                numberOfEarsDeployed++;
                log.info("deployed Ear:" + files[i].getName());
            } catch (Exception ex) {
                // TODO Auto-generated catch block
                log.info("Could not deploy Ear:" + file.getName(), ex);
                //e.printStackTrace();
            }
            // logger.info("filePath"+filePath);
            /*filePath = filePath.substring(0, filePath.toLowerCase()
                  .lastIndexOf(".ear"));
            VFSClassLoader customClassLoader = null;
            try {
               CopyOnWriteArrayList<FileObject> fileObjects = new CopyOnWriteArrayList<FileObject>();
               System.out.println("EARFILE:/   \n\n\n\n\n\n\n\n\n\n"
             + earFile);
               obtainUrls(earFile, earFile, fileObjects, jarClassListMap,
             fsManager);
               System.out.println(fileObjects);
               System.out.println(jarClassListMap);
               VFSClassLoader customClassLoaderBaseLib = new VFSClassLoader(
             fileObjects.toArray(new FileObject[fileObjects
                   .size()]), fsManager, Thread
                   .currentThread().getContextClassLoader());
               // customClassLoader.loadClass(classList.get(0).toString());
                    
               Set keys = jarClassListMap.keySet();
               Iterator key = keys.iterator();
               for (int keyCount = 0; keyCount < keys.size(); keyCount++) {
                  FileObject jarFileObject = (FileObject) key.next();
                  classList = (CopyOnWriteArrayList<String>) jarClassListMap
                .get(jarFileObject);
                  for (int classCount = 0; classCount < classList.size(); classCount++) {
             String classwithpackage = classList.get(classCount)
                   .substring(
                         0,
                         classList.get(classCount).indexOf(
                               ".class"));
             classwithpackage = classwithpackage.replace("/",
                   ".");
             System.out.println("classList:"
                   + classwithpackage.replace("/", "."));
             try {
                if (!classwithpackage.contains("$")) {
                   customClassLoader = new VFSClassLoader(
                         jarFileObject, fsManager,
                         customClassLoaderBaseLib);
                   this.urlClassLoaderMap.put(scanDirectory
                         + "/"
                         + files[i].getName()
                         + "/"
                         + jarFileObject.getName()
                               .getBaseName(),
                         customClassLoader);
                   Class executorServiceClass = customClassLoader
                         .loadClass(classwithpackage);
                   System.out.println(executorServiceClass
                         .newInstance());
                   // System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                   // System.out.println();
                   Method[] methods = executorServiceClass
                         .getMethods();
                   for (Method method : methods) {
                      Annotation[] annotations = method
                            .getDeclaredAnnotations();
                      for (Annotation annotation : annotations) {
                         if (annotation instanceof ExecutorServiceAnnot) {
                            ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation;
                            ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo();
                            executorServiceInfo
                                  .setExecutorServicesClass(executorServiceClass);
                            executorServiceInfo
                                  .setMethod(method);
                            executorServiceInfo
                                  .setMethodParams(method
                                        .getParameterTypes());
                            // System.out.println("method="+executorServiceAnnot.servicename());
                            // System.out.println("method info="+executorServiceInfo);
                            // if(servicesMap.get(executorServiceAnnot.servicename())==null)throw
                            // new Exception();
                            executorServiceMap.put(
                                  executorServiceAnnot
                                        .servicename(),
                                  executorServiceInfo);
                         }
                      }
                   }
                    
                }
             } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
             } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
             } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
             }
                  }
                  jarFileObject.close();
               }
               for (FileObject fobject : fileObjects) {
                  fobject.close();
               }
            } catch (FileSystemException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
            try {
               earFile.close();
               fsManager.closeFileSystem(earFile.getFileSystem());
            } catch (FileSystemException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }*/
        }
    }
    //fsManager.close();
    if (exec == null) {
        exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(task, 0, 1000, TimeUnit.MILLISECONDS);
    }
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.common.source.AbstractCswSource.java

/**
 * Instantiates a CswSource. This constructor is for unit tests
 *
 * @param context                The {@link BundleContext} from the OSGi Framework
 * @param cswSourceConfiguration the configuration of this source
 * @param provider               transform provider to transform results
 * @param factory                client factory already configured for this source
 *//*from   ww w .jav a2s  .  co m*/
public AbstractCswSource(BundleContext context, CswSourceConfiguration cswSourceConfiguration,
        Converter provider, SecureCxfClientFactory factory) {
    this.context = context;
    this.cswSourceConfiguration = cswSourceConfiguration;
    this.cswTransformConverter = provider;
    scheduler = Executors.newSingleThreadScheduledExecutor();
    this.factory = factory;
    setConsumerMap();
}

From source file:com.cityfreqs.littlesirecho.MainActivity.java

private void runScheduler() {
    PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakeLock.acquire();/*from w ww .jav  a2 s.co m*/

    scheduler = Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleAtFixedRate(new Runnable() {
        public void run() {
            logger("executor echo.");
            echoNotification();
        }
    }, userSelectedWaitTime, userSelectedWaitTime, TimeUnit.MILLISECONDS);
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.common.source.AbstractCswSource.java

/**
 * Instantiates a CswSource.//from   ww  w .j av a 2  s  .  c om
 */
public AbstractCswSource() {
    cswSourceConfiguration = new CswSourceConfiguration();
    scheduler = Executors.newSingleThreadScheduledExecutor();
}

From source file:org.dcm4che.tool.dcmqrscp.DcmQRSCP.java

public static void main(String[] args) {
    try {//from  www.java2s  .  co  m
        CommandLine cl = parseComandLine(args);
        DcmQRSCP main = new DcmQRSCP();
        CLIUtils.configure(main.fsInfo, cl);
        CLIUtils.configureBindServer(main.conn, main.ae, cl);
        CLIUtils.configure(main.conn, cl);
        configureDicomFileSet(main, cl);
        configureTransferCapability(main, cl);
        configureInstanceAvailability(main, cl);
        configureStgCmt(main, cl);
        configureSendPending(main, cl);
        configureRemoteConnections(main, cl);
        ExecutorService executorService = Executors.newCachedThreadPool();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        main.device.setScheduledExecutor(scheduledExecutorService);
        main.device.setExecutor(executorService);
        main.device.bindConnections();
    } catch (ParseException e) {
        System.err.println("dcmqrscp: " + e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println("dcmqrscp: " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:org.apache.lens.server.session.HiveSessionService.java

@Override
public synchronized void start() {
    super.start();

    sessionExpiryThread = Executors.newSingleThreadScheduledExecutor();
    int sessionExpiryInterval = getSessionExpiryInterval();
    sessionExpiryThread.scheduleWithFixedDelay(sessionExpiryRunnable, sessionExpiryInterval,
            sessionExpiryInterval, TimeUnit.SECONDS);

    // Restore sessions if any
    if (restorableSessions == null || restorableSessions.size() <= 0) {
        log.info("No sessions to restore");
        return;/* w w w .j  a v  a 2 s . c  o m*/
    }

    for (LensSessionImpl.LensSessionPersistInfo persistInfo : restorableSessions) {
        try {
            LensSessionHandle sessionHandle = persistInfo.getSessionHandle();
            restoreSession(sessionHandle, persistInfo.getUsername(), persistInfo.getPassword());
            LensSessionImpl session = getSession(sessionHandle);
            session.getLensSessionPersistInfo().setLastAccessTime(persistInfo.getLastAccessTime());
            session.getLensSessionPersistInfo().setConfig(persistInfo.getConfig());
            session.getLensSessionPersistInfo().setResources(persistInfo.getResources());
            session.setCurrentDatabase(persistInfo.getDatabase());
            session.getLensSessionPersistInfo().setMarkedForClose(persistInfo.isMarkedForClose());

            // Add resources for restored sessions
            for (LensSessionImpl.ResourceEntry resourceEntry : session.getResources()) {
                try {
                    addResourceUponRestart(sessionHandle, resourceEntry);
                } catch (Exception e) {
                    log.error("Failed to restore resource for session: " + session + " resource: "
                            + resourceEntry, e);
                }
            }

            // Add config for restored sessions
            try {
                setSessionParametersOnRestore(sessionHandle, session.getConfig());
            } catch (Exception e) {
                log.error("Error setting parameters " + session.getConfig() + " for session: " + session, e);
            }
            log.info("Restored session " + persistInfo.getSessionHandle().getPublicId());
            notifyEvent(new SessionRestored(System.currentTimeMillis(), sessionHandle));
        } catch (LensException e) {
            throw new RuntimeException(e);
        }
    }
    log.info("Session service restored " + restorableSessions.size() + " sessions");
}

From source file:org.sakaiproject.authz.impl.DbAuthzGroupService.java

/**
 * Final initialization, once all dependencies are set.
 *//*from   w  ww  .j  av a2 s.  c o  m*/
public void init() {
    try {
        // The observer will be notified whenever there are new events. Priority observers get notified first, before normal observers.
        eventTrackingService().addPriorityObserver(this);

        // if we are auto-creating our schema, check and create
        if (m_autoDdl) {
            sqlService().ddl(this.getClass().getClassLoader(), "sakai_realm");
        }

        super.init();
        setDbAuthzGroupSql(sqlService().getVendor());

        // pre-cache role and function names
        cacheRoleNames();
        cacheFunctionNames();
        m_realmRoleGRCache = m_memoryService
                .newCache("org.sakaiproject.authz.impl.DbAuthzGroupService.realmRoleGroupCache");
        M_log.info("init(): table: " + m_realmTableName + " external locks: " + m_useExternalLocks);

        authzUserGroupIdsCache = m_memoryService
                .newCache("org.sakaiproject.authz.impl.DbAuthzGroupService.authzUserGroupIdsCache");

        maintainRolesCache = m_memoryService
                .newCache("org.sakaiproject.authz.impl.DbAuthzGroupService.maintainRolesCache");
        //get the set of maintain roles and cache them on startup
        getMaintainRoles();

        refreshTaskInterval = initConfig(REFRESH_INTERVAL_PROPKEY,
                serverConfigurationService().getString(REFRESH_INTERVAL_PROPKEY), refreshTaskInterval);
        refreshMaxTime = initConfig(REFRESH_MAX_TIME_PROPKEY,
                serverConfigurationService().getString(REFRESH_MAX_TIME_PROPKEY), refreshMaxTime);

        refreshQueue = Collections.synchronizedMap(new HashMap<String, AuthzGroup>());

        refreshScheduler = Executors.newSingleThreadScheduledExecutor();
        refreshScheduler.scheduleWithFixedDelay(new RefreshAuthzGroupTask(), 120, // minimally wait 2 mins for sakai to start
                refreshTaskInterval, // delay before running again
                TimeUnit.SECONDS);
    } catch (Exception t) {
        M_log.warn("init(): ", t);
    }
}