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.smartx.bill.mepad.mestore.uimgloader.AbsListViewBaseActivity.java

protected void cancelDialog(boolean status) {
    if (status) {
        findViewById(id.me_topView).setVisibility(View.VISIBLE);
    } else if (!status) {
        findViewById(id.me_topView).setVisibility(View.INVISIBLE);
    }//from  ww w.  j a va  2 s . c o m
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    Runnable runner = new Runnable() {
        public void run() {
            dialog.dismiss();
        }
    };
    executor.schedule(runner, LayoutResourcesDatas.DELAY_TIME, TimeUnit.MILLISECONDS);
}

From source file:org.codice.alliance.nsili.source.NsiliSource.java

/**
 * Constructor used for testing.//from ww  w  .  j av a 2s  . co  m
 */
NsiliSource(SecureCxfClientFactory factory, HashMap<String, String[]> resultAttributes,
        HashMap<String, List<String>> sortableAttributes, NsiliFilterDelegate filterDelegate, ORB orb) {
    scheduler = Executors.newSingleThreadScheduledExecutor();
    this.factory = factory;
    this.resultAttributes = resultAttributes;
    this.nsiliFilterDelegate = filterDelegate;
    this.sortableAttributes = sortableAttributes;
    ddfOrgName = System.getProperty("org.codice.ddf.system.organization", DEFAULT_USER_INFO);
    this.orb = orb;
}

From source file:at.wada811.android.library.demos.concurrent.ExecutorActivity.java

/**
 * {@link ScheduledExecutorService#scheduleWithFixedDelay(Runnable, long, long, TimeUnit)}
 * ?????//from w w w  . j  av a 2 s  .c om
 * 
 * <p>
 * ??????????????????????
 * </p>
 */
public void newSingleThreadScheduledExecutorWithFixedDelayTest() {
    LogUtils.d();
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleWithFixedDelay(new ExecutorRunnable("A", 1), 1, 2, TimeUnit.SECONDS);
    shutdown(executorService);
}

From source file:org.codice.alliance.nsili.source.NsiliSource.java

public NsiliSource(CorbaOrb corbaOrb) {
    scheduler = Executors.newSingleThreadScheduledExecutor();
    setCorbaOrb(corbaOrb);
}

From source file:io.fabric8.kubernetes.client.dsl.internal.RollingUpdater.java

/**
 * Since k8s v1.4.x, rc/rs deletes are asynchronous.
 * Lets wait until the resource is actually deleted in the server
 *///from ww w. j a v  a 2 s.co m
private void waitUntilDeleted(final String namespace, final String name) {
    final CountDownLatch countDownLatch = new CountDownLatch(1);

    final Runnable waitTillDeletedPoller = new Runnable() {
        public void run() {
            try {
                T res = resources().inNamespace(namespace).withName(name).get();
                if (res == null) {
                    countDownLatch.countDown();
                }
            } catch (KubernetesClientException e) {
                if (e.getCode() == 404) {
                    countDownLatch.countDown();
                }
            }
        }
    };

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture poller = executor.scheduleWithFixedDelay(waitTillDeletedPoller, 0, 5, TimeUnit.SECONDS);
    ScheduledFuture logger = executor.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            LOG.debug("Found resource {}/{} not yet deleted on server, so waiting...", namespace, name);
        }
    }, 0, loggingIntervalMillis, TimeUnit.MILLISECONDS);
    try {
        countDownLatch.await(DEFAULT_SERVER_GC_WAIT_TIMEOUT, TimeUnit.MILLISECONDS);
        executor.shutdown();
    } catch (InterruptedException e) {
        poller.cancel(true);
        logger.cancel(true);
        executor.shutdown();
        LOG.warn("Still found deleted resource {} in namespace: {}  after waiting for {} seconds so giving up",
                name, namespace, TimeUnit.MILLISECONDS.toSeconds(DEFAULT_SERVER_GC_WAIT_TIMEOUT));
    }
}

From source file:com.sitewhere.android.example.ExampleFragment.java

/**
 * Only schedule SiteWhere reporting thread once we have a connection to the server.
 *///w  w  w.j  a  v  a2  s  .c o m
public void startDeviceMonitoring() {
    Log.d(TAG, "Starting device monitoring.");

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // Start location updates.
            boolean locationStarted = false;
            locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
            if (ActivityCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getActivity(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "No permissions for location. Requesting permissions from user.");
                requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION }, LOCATION_REQUEST_CODE);
                return;
            }
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                        ExampleFragment.this);
                locationStarted = true;
                Log.d(TAG, "Started monitoring locations via GPS provider.");
            } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                        ExampleFragment.this);
                locationStarted = true;
                Log.d(TAG, "Started monitoring locations via network provider.");
            } else {
                locationStarted = false;
                Log.d(TAG, "No location provider available. Will not monitor location.");
            }

            // Start accelerometer updates.
            boolean accelerometerStarted = false;
            sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
                rotationVector = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
                sensorManager.registerListener(ExampleFragment.this, rotationVector,
                        SensorManager.SENSOR_DELAY_NORMAL);
                accelerometerStarted = true;
                Log.d(TAG, "Started monitoring accelerometer.");
            } else {
                Toast.makeText(getActivity().getApplicationContext(),
                        "Unable to start accelerometer updates. No accelerometer provided", Toast.LENGTH_LONG);
                accelerometerStarted = false;
                Log.d(TAG, "Unable to monitor accelerometer.");
            }

            // Send alerts to SiteWhere.
            SiteWhereMessageClient messageClient = SiteWhereMessageClient.getInstance();
            try {
                if (locationStarted)
                    messageClient.sendDeviceAlert(messageClient.getUniqueDeviceId(), "location.started",
                            "Started to read location data.", null);
            } catch (SiteWhereMessagingException ex) {
                Log.e(TAG, "Unable to send location.started alert to SiteWhere.");
            }
            try {
                if (accelerometerStarted)
                    messageClient.sendDeviceAlert(messageClient.getUniqueDeviceId(), "accelerometer.started",
                            "Started to read accelerometer data.", null);
            } catch (SiteWhereMessagingException e) {
                Log.e(TAG, "Unable to send accelerometer.started alert to SiteWhere.");
            }

            if (scheduler != null) {
                scheduler.shutdownNow();
            }
            scheduler = Executors.newSingleThreadScheduledExecutor();
            scheduler.scheduleAtFixedRate(new SiteWhereDataReporter(), SEND_INTERVAL_IN_SECONDS,
                    SEND_INTERVAL_IN_SECONDS, TimeUnit.SECONDS);
            Log.d(TAG, "Set up scheduler for monitoring.");
        }
    });
}

From source file:org.codice.ddf.spatial.ogc.wfs.v2_0_0.catalog.source.WfsSource.java

public WfsSource() {
    // Required for bean creation
    LOGGER.debug("Creating {}", WfsSource.class.getName());
    scheduler = Executors.newSingleThreadScheduledExecutor();
}

From source file:org.apache.lens.ml.impl.LensMLImpl.java

/**
 * Start./*from  w  ww  .ja v a  2  s .  c om*/
 */
public synchronized void start() {
    for (MLDriver driver : drivers) {
        try {
            if (driver instanceof SparkMLDriver && sparkContext != null) {
                ((SparkMLDriver) driver).useSparkContext(sparkContext);
            }
            driver.start();
        } catch (LensException e) {
            log.error("Failed to start driver " + driver, e);
        }
    }

    udfStatusExpirySvc = Executors.newSingleThreadScheduledExecutor();
    udfStatusExpirySvc.scheduleAtFixedRate(new UDFStatusExpiryRunnable(), 60, 60, TimeUnit.SECONDS);

    log.info("Started ML service");
}

From source file:org.j2free.config.ConfigurationListener.java

/**
 *
 * @param event/* w w w . ja  v a  2  s.co  m*/
 */
public synchronized void contextInitialized(ServletContextEvent event) {
    context = event.getServletContext();

    // Get the configuration file
    String configPathTemp = (String) context.getInitParameter(INIT_PARAM_CONFIG_PATH);

    // Use the default path if it wasn't specified
    if (StringUtils.isBlank(configPathTemp))
        configPathTemp = DEFAULT_CONFIG_PATH;

    // Finalize the config path (needs to be final for inner-Runnable below)
    final String configPath = configPathTemp;
    context.setAttribute(CONTEXT_ATTR_CONFIG_PATH, configPath);

    try {
        // Load the configuration
        DefaultConfigurationBuilder configBuilder = new DefaultConfigurationBuilder();
        configBuilder.setFileName(configPath);

        final CombinedConfiguration config = configBuilder.getConfiguration(true);

        // Save the config where we can get at it later
        context.setAttribute(CONTEXT_ATTR_CONFIG, config);
        Global.put(CONTEXT_ATTR_CONFIG, config);

        // Determine the localhost
        String localhost = config.getString(PROP_LOCALHOST, "ip");
        if (localhost.equalsIgnoreCase("ip")) {
            try {
                localhost = InetAddress.getLocalHost().getHostAddress();
                log.info("Using localhost: " + localhost);
            } catch (Exception e) {
                log.warn("Error determining localhost", e);
                localhost = "localhost";
            }
        }

        context.setAttribute(CONTEXT_ATTR_LOCALHOST, localhost);
        Global.put(CONTEXT_ATTR_LOCALHOST, localhost);
        loadedConfigPropKeys.add(CONTEXT_ATTR_LOCALHOST);

        // Set application context attributes for all config properties
        String prop, value;
        Iterator itr = config.getKeys();
        while (itr.hasNext()) {
            prop = (String) itr.next();
            value = config.getString(prop);

            // Anything with the value "localhost" will be set to the IP if possible
            value = (value.equals("localhost") ? localhost : value);

            log.debug("Config: " + prop + " = " + value);
            context.setAttribute(prop, value);
            loadedConfigPropKeys.add(prop);
        }

        // Run Mode configuration
        String runMode = config.getString(PROP_RUNMODE);
        try {
            RUN_MODE = RunMode.valueOf(runMode);
        } catch (Exception e) {
            log.warn("Error setting runmode, invalid value: " + runMode);
        }

        context.setAttribute("devMode", RUN_MODE != RunMode.PRODUCTION);
        loadedConfigPropKeys.add("devMode");

        // Fragment Cache Configuration
        if (config.getBoolean(FragmentCache.Properties.ENABLED, false)) {
            log.info("Enabling fragment caching...");
            FragmentCacheTag.enable();

            // This is expected to be in seconds
            long temp = config.getLong(FragmentCache.Properties.REQUEST_TIMEOUT, -1l);
            if (temp != -1) {
                log.info("Setting FragmentCacheTag request timeout: " + temp);
                FragmentCacheTag.setRequestTimeout(temp);
            }

            // The property is in seconds, but WARNING_COMPUTE_DURATION does NOT use a TimeUnit, so it's in ms
            temp = config.getLong(FragmentCache.Properties.WARNING_DURATION, -1l);
            if (temp != -1) {
                log.info("Setting FragmentCacheTag warning duration: " + temp);
                FragmentCacheTag.setWarningComputeDuration(temp * 1000);
            }

            // Get the fragment cache names
            String[] cacheNames = config.getStringArray(FragmentCache.Properties.ENGINE_NAMES);
            for (String cacheName : cacheNames) {
                String cacheClassName = config
                        .getString(String.format(FragmentCache.Properties.ENGINE_CLASS_TEMPLATE, cacheName));
                try {
                    // Load up the class
                    Class<? extends FragmentCache> cacheClass = (Class<? extends FragmentCache>) Class
                            .forName(cacheClassName);

                    // Look for a constructor that takes a config
                    Constructor<? extends FragmentCache> constructor = null;
                    try {
                        constructor = cacheClass.getConstructor(Configuration.class);
                    } catch (Exception e) {
                    }

                    FragmentCache cache;

                    // If we found the configuration constructor, use it
                    if (constructor != null)
                        cache = constructor.newInstance(config);
                    else {
                        // otherwise use a default no-args constructor
                        log.warn("Could not find a " + cacheClass.getSimpleName()
                                + " constructor that takes a Configuration, defaulting to no-args constructor");
                        cache = cacheClass.newInstance();
                    }

                    // register the cache with the FragmentCacheTag using the config strategy-name, or the engineName
                    // if a strategy-name is not specified
                    log.info("Registering FragmentCache strategy: [name=" + cacheName + ", class="
                            + cacheClass.getName() + "]");
                    FragmentCacheTag.registerStrategy(cacheName, cache);
                } catch (Exception e) {
                    log.error("Error enabling FragmentCache engine: " + cacheName, e);
                }
            }

        } else {
            // Have to call this here, because reconfiguration could turn
            // the cache off after it was previously enabled.
            FragmentCacheTag.disable();
        }

        // For Task execution
        ScheduledExecutorService taskExecutor;

        if (config.getBoolean(PROP_TASK_EXECUTOR_ON, false)) {
            int threads = config.getInt(PROP_TASK_EXECUTOR_THREADS, DEFAULT_TASK_EXECUTOR_THREADS);

            if (threads == 1)
                taskExecutor = Executors.newSingleThreadScheduledExecutor();
            else
                taskExecutor = Executors.newScheduledThreadPool(threads);

            context.setAttribute(CONTEXT_ATTR_TASK_MANAGER, taskExecutor);
            loadedConfigPropKeys.add(CONTEXT_ATTR_TASK_MANAGER);

            Global.put(CONTEXT_ATTR_TASK_MANAGER, taskExecutor);
        } else {
            // Not allowed to shutdown the taskExecutor if dynamic reconfig is enabled
            if (reconfigTask == null) {
                // Shutdown and remove references to the taskManager previously created
                taskExecutor = (ScheduledExecutorService) Global.get(CONTEXT_ATTR_TASK_MANAGER);
                if (taskExecutor != null) {
                    taskExecutor.shutdown(); // will block until all tasks complete
                    taskExecutor = null;
                    Global.remove(CONTEXT_ATTR_TASK_MANAGER);
                }
            } else {
                // We could just log a warning that you can't do this, but the user
                // might not see that, so we're going to refuse to reset a configuration
                // that cannot be loaded in whole successfully.
                throw new ConfigurationException(
                        "Cannot disable task execution service, dynamic reconfiguration is enabled!");
            }
        }

        // Email Service
        if (config.getBoolean(PROP_MAIL_SERVICE_ON, false)) {
            if (!SimpleEmailService.isEnabled()) {
                // Get the SMTP properties
                Properties props = System.getProperties();
                props.put(PROP_SMTP_HOST, config.getString(PROP_SMTP_HOST));
                props.put(PROP_SMTP_PORT, config.getString(PROP_SMTP_PORT));
                props.put(PROP_SMTP_AUTH, config.getString(PROP_SMTP_AUTH));

                Session session;

                if (config.getBoolean(PROP_SMTP_AUTH)) {
                    final String user = config.getString(PROP_SMTP_USER);
                    final String pass = config.getString(PROP_SMTP_PASS);

                    Authenticator auth = new Authenticator() {
                        @Override
                        public PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(user, pass);
                        }
                    };
                    session = Session.getInstance(props, auth);

                } else {
                    session = Session.getInstance(props);
                }

                // Get the global headers
                Iterator headerNames = config.getKeys(PROP_MAIL_HEADER_PREFIX);
                List<KeyValuePair<String, String>> headers = new LinkedList<KeyValuePair<String, String>>();

                String headerName;
                while (headerNames.hasNext()) {
                    headerName = (String) headerNames.next();
                    headers.add(new KeyValuePair<String, String>(headerName, config.getString(headerName)));
                }

                // Initialize the service
                SimpleEmailService.init(session);
                SimpleEmailService.setGlobalHeaders(headers);

                // Set whether we actually send the e-mails
                SimpleEmailService.setDummyMode(config.getBoolean(PROP_MAIL_DUMMY_MODE, false));

                // Set the failure policy
                String policy = config.getString(PROP_MAIL_ERROR_POLICY);
                if (policy != null) {
                    if (policy.equals(VALUE_MAIL_POLICY_DISCARD)) {
                        SimpleEmailService.setErrorPolicy(new SimpleEmailService.DiscardPolicy());
                    } else if (policy.equals(VALUE_MAIL_POLICY_REQUEUE)) {
                        Priority priority = null;
                        try {
                            priority = Priority.valueOf(config.getString(PROP_MAIL_REQUEUE_PRIORITY));
                        } catch (Exception e) {
                            log.warn("Error reading requeue policy priority: "
                                    + config.getString(PROP_MAIL_REQUEUE_PRIORITY, "") + ", using default");
                        }

                        if (priority == null)
                            SimpleEmailService.setErrorPolicy(new SimpleEmailService.RequeuePolicy());
                        else
                            SimpleEmailService.setErrorPolicy(new SimpleEmailService.RequeuePolicy(priority));
                    }
                }

                // Parse templates
                String emailTemplateDir = config.getString(PROP_MAIL_TEMPLATE_DIR);

                // If the template
                if (StringUtils.isBlank(emailTemplateDir))
                    emailTemplateDir = DEFAULT_EMAIL_TEMPLATE_DIR;

                log.debug("Looking for e-mail templates in: " + emailTemplateDir);
                Set<String> templates = context.getResourcePaths(emailTemplateDir);

                // E-mail templates
                if (templates != null && !templates.isEmpty()) {
                    log.debug("Found " + templates.size() + " templates");

                    String key;
                    String defaultTemplate = config.getString(PROP_MAIL_DEFAULT_TEMPLATE, EMPTY);

                    InputStream in;
                    StringBuilder builder;
                    Scanner scanner;

                    try {
                        Template template;
                        String[] parts;

                        ContentType contentType;

                        for (String path : templates) {
                            path = path.trim();
                            parts = path.split("\\.");

                            contentType = ContentType.valueOfExt(parts[1]);

                            try {
                                in = context.getResourceAsStream(path.trim());

                                if (in != null && in.available() > 0) {
                                    scanner = new Scanner(in);
                                    builder = new StringBuilder();

                                    while (scanner.hasNextLine()) {
                                        builder.append(scanner.nextLine());
                                        if (contentType == ContentType.PLAIN) {
                                            builder.append("\n");
                                        }
                                    }

                                    template = new Template(builder.toString(), contentType);

                                    key = parts[0].replace(emailTemplateDir, EMPTY);
                                    SimpleEmailService.registerTemplate(key, template,
                                            key.equals(defaultTemplate));
                                }
                            } catch (IOException ioe) {
                                log.error("Error loading e-mail template: " + path, ioe);
                            }
                        }
                    } catch (Exception e) {
                        log.error("Error loading e-mail templates", e);
                    }
                } else
                    log.debug("No e-mail templates found.");
            }
        } else if (SimpleEmailService.isEnabled()) {
            boolean shutdown = false;
            try {
                shutdown = SimpleEmailService.shutdown(30, TimeUnit.SECONDS);
            } catch (InterruptedException ie) {
                log.warn("Interrupted while shutting down SimpleEmailService");
            }

            if (!shutdown)
                SimpleEmailService.shutdown();
        }

        // QueuedHttpCallService
        if (config.getBoolean(PROP_HTTP_SRVC_ON, false)) {
            if (!SimpleHttpService.isEnabled()) // Don't double init...
            {
                int defaultThreadCount = Runtime.getRuntime().availableProcessors() + 1; // threads to use if unspecified
                SimpleHttpService.init(config.getInt(PROP_HTTP_SRVC_CORE_POOL, defaultThreadCount),
                        config.getInt(PROP_HTTP_SRVC_MAX_POOL, defaultThreadCount),
                        config.getLong(PROP_HTTP_SRVC_POOL_IDLE, DEFAULT_HTTP_SRVC_THREAD_IDLE),
                        config.getInt(PROP_HTTP_SRVC_CONNECT_TOUT, DEFAULT_HTTP_SRVC_CONNECT_TOUT),
                        config.getInt(PROP_HTTP_SRVE_SOCKET_TOUT, DEFAULT_HTTP_SRVE_SOCKET_TOUT));
            }
        } else if (SimpleHttpService.isEnabled()) {
            boolean shutdown = false;
            try {
                // Try to shutdown the service while letting currently waiting tasks complete
                shutdown = SimpleHttpService.shutdown(30, TimeUnit.SECONDS);
            } catch (InterruptedException ie) {
                log.warn("Interrupted while waiting for SimpleHttpService to shutdown");
            }
            if (!shutdown) {
                // But if that doesn't finish in 60 seconds, just cut it off
                int count = SimpleHttpService.shutdown().size();
                log.warn("SimpleHttpService failed to shutdown in 60 seconds, so it was terminated with "
                        + count + " tasks waiting");
            }
        }

        // Spymemcached Client
        if (config.getBoolean(PROP_SPYMEMCACHED_ON, false)) {
            String addresses = config.getString(PROP_SPYMEMCACHED_ADDRESSES);
            if (addresses == null) {
                log.error("Error configuring spymemcached; enabled but no addresses!");
            } else {
                try {
                    // Reflect our way to the constructor, this is all so that the
                    // spymemcached jar does not need to be included in a J2Free app
                    // unless it is actually to be used.
                    Class klass = Class.forName("net.spy.memcached.MemcachedClient");
                    Constructor constructor = klass.getConstructor(List.class);

                    klass = Class.forName("net.spy.memcached.AddrUtil");
                    Method method = klass.getMethod("getAddresses", String.class);

                    Object client = constructor.newInstance(method.invoke(null, addresses));

                    context.setAttribute(CONTEXT_ATTR_SPYMEMCACHED, client);
                    loadedConfigPropKeys.add(CONTEXT_ATTR_SPYMEMCACHED);

                    Global.put(CONTEXT_ATTR_SPYMEMCACHED, client);

                    log.info("Spymemcached client created, connected to " + addresses);
                } catch (Exception e) {
                    log.error("Error creating memcached client [addresses=" + addresses + "]", e);
                }
            }
        } else {
            // If a spymemcached client was previous created
            Object client = Global.get(CONTEXT_ATTR_SPYMEMCACHED);
            if (client != null) {
                try {
                    // Reflect our way to the shutdown method
                    Class klass = Class.forName("net.spy.memcached.MemcachedClient");
                    Method method = klass.getMethod("shutdown");

                    method.invoke(null, client); // and shut it down

                    log.info("Spymemcached client shutdown");
                } catch (Exception e) {
                    log.error("Error shutting down spymemcached client", e);
                }

                // Then remove any references
                Global.remove(CONTEXT_ATTR_SPYMEMCACHED);
                client = null;
            }
        }
    } catch (ConfigurationException ce) {
        log.error("Error configuring app", ce);
    }
}

From source file:com.mch.registry.ccs.server.CcsClient.java

/**
 * Sends messages to registered devices/*from w w  w .  j  a  v a 2 s.  co  m*/
 */
public static void main(String[] args) {

    Config config = new Config();
    final String projectId = config.getProjectId();
    final String key = config.getKey();

    final CcsClient ccsClient = CcsClient.prepareClient(projectId, key, true);

    try {
        ccsClient.connect();
    } catch (XMPPException e) {
        logger.log(Level.WARNING, "XMPP Exception ", e);
    }

    final Runnable sendNotifications = new Runnable() {
        public void run() {
            try {
                logger.log(Level.INFO, "Working Q!");
                if (!isOffHours()) {
                    //Prepare downstream message
                    String toRegId = "";
                    String message = "";
                    String messageId = "";
                    Map<String, String> payload = new HashMap<String, String>();
                    String collapseKey = null;
                    Long timeToLive = 10000L;
                    Boolean delayWhileIdle = true;
                    String messagePrefix = "";
                    int notificationQueueID = 0;
                    boolean sucessfullySent = false;

                    //Read from mysql database
                    MySqlHandler mysql = new MySqlHandler();
                    ArrayList<Notification> queue = new ArrayList<Notification>();

                    for (int i = 1; i < 3; i++) {
                        queue = mysql.getNotificationQueue(i);
                        if (queue.size() > 0) {

                            switch (i) {
                            case 1:
                                messagePrefix = "_V: ";
                                break;
                            case 2:
                                messagePrefix = "_R: ";
                                break;
                            default:
                                messagePrefix = "";
                                logger.log(Level.WARNING, "Unknown message type!");
                            }

                            Notification notification = new Notification();
                            Iterator<Notification> iterator = queue.iterator();

                            while (iterator.hasNext()) {
                                notification = iterator.next();

                                toRegId = notification.getGcmRegID();
                                message = notification.getNotificationText();
                                notificationQueueID = notification.getNotificationQueueID();
                                messageId = "m-" + Long.toString(random.nextLong());

                                payload = new HashMap<String, String>();
                                payload.put("message", messagePrefix + message);

                                try {
                                    // Send the downstream message to a device.
                                    ccsClient.send(createJsonMessage(toRegId, messageId, payload, collapseKey,
                                            timeToLive, delayWhileIdle));
                                    sucessfullySent = true;
                                    logger.log(Level.INFO, "Message sent. ID: " + notificationQueueID
                                            + ", RegID: " + toRegId + ", Text: " + message);
                                } catch (Exception e) {
                                    mysql.prepareNotificationForTheNextDay(notificationQueueID);
                                    sucessfullySent = false;
                                    logger.log(Level.WARNING,
                                            "Message could not be sent! ID: " + notificationQueueID
                                                    + ", RegID: " + toRegId + ", Text: " + message);
                                }

                                if (sucessfullySent) {
                                    mysql.moveNotificationToHistory(notificationQueueID);
                                }
                            }
                        } else {
                            logger.log(Level.INFO, "No notifications to send. Type: " + Integer.toString(i));
                        }
                    }
                }
            } catch (Exception e) {
                logger.log(Level.WARNING, "Exception ", e);
            }
        }
    };

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    //Start when server starts and every 30 minutes after
    ScheduledFuture task = executor.scheduleAtFixedRate(sendNotifications, 0, 30, TimeUnit.MINUTES);
    try {
        task.get();
    } catch (ExecutionException e) {
        logger.log(Level.SEVERE, "Exception ", e);
    } catch (InterruptedException e) {
        logger.log(Level.SEVERE, "Exception ", e);
    }
    task.cancel(false);

    try {
        executor.shutdown();
        executor.awaitTermination(30, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        logger.log(Level.SEVERE, "Exception ", e);
    }

}