Example usage for java.util.concurrent Executors newScheduledThreadPool

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

Introduction

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

Prototype

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 

Source Link

Document

Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.

Usage

From source file:org.apache.hama.bsp.GroomServer.java

public synchronized void initialize() throws IOException {
    if (this.conf.get(Constants.PEER_HOST) != null) {
        this.localHostname = conf.get(Constants.PEER_HOST);
    }/*  w  w w  .j ava  2s . c  o  m*/

    if (localHostname == null) {
        this.localHostname = DNS.getDefaultHost(conf.get("bsp.dns.interface", "default"),
                conf.get("bsp.dns.nameserver", "default"));
    }
    // check local disk
    checkLocalDirs(getLocalDirs());
    deleteLocalFiles(SUBDIR);

    // Clear out state tables
    this.tasks.clear();
    this.runningJobs = new TreeMap<BSPJobID, RunningJob>();
    this.runningTasks = new ConcurrentHashMap<TaskAttemptID, TaskInProgress>();
    this.finishedTasks = new LinkedHashMap<TaskAttemptID, TaskInProgress>();
    this.conf.set(Constants.PEER_HOST, localHostname);
    this.conf.set(Constants.GROOM_RPC_HOST, localHostname);
    this.maxCurrentTasks = conf.getInt(Constants.MAX_TASKS_PER_GROOM, 3);
    this.assignedPeerNames = new HashMap<TaskAttemptID, Integer>(2 * this.maxCurrentTasks);

    int rpcPort = -1;
    String rpcAddr = null;
    if (false == this.initialized) {
        rpcAddr = conf.get(Constants.GROOM_RPC_HOST, Constants.DEFAULT_GROOM_RPC_HOST);
        rpcPort = conf.getInt(Constants.GROOM_RPC_PORT, Constants.DEFAULT_GROOM_RPC_PORT);
        if (-1 == rpcPort || null == rpcAddr)
            throw new IllegalArgumentException("Error rpc address " + rpcAddr + " port" + rpcPort);
        this.workerServer = RPC.getServer(this, rpcAddr, rpcPort, conf);
        this.workerServer.start();
        this.rpcServer = rpcAddr + ":" + rpcPort;
    }

    server = new HttpServer("groomserver", rpcAddr,
            conf.getInt("bsp.http.groomserver.port", Constants.DEFAULT_GROOM_INFO_SERVER), true, conf);

    FileSystem local = FileSystem.getLocal(conf);
    server.setAttribute("groom.server", this);
    server.setAttribute("local.file.system", local);
    server.setAttribute("conf", conf);
    server.setAttribute("log", LOG);
    server.addServlet("taskLog", "/tasklog", TaskLogServlet.class);

    LOG.info("starting webserver: " + rpcAddr);
    server.start();

    String address = BSPNetUtils.getServerAddress(conf, "bsp.groom.report.bindAddress", "bsp.groom.report.port",
            "bsp.groom.report.address");
    InetSocketAddress socAddr = BSPNetUtils.createSocketAddr(address);
    String bindAddress = socAddr.getHostName();
    int tmpPort = socAddr.getPort();

    // RPC initialization
    this.taskReportServer = RPC.getServer(this, bindAddress, tmpPort,
            conf.getInt("hama.groom.report.server.handler.threads.num", 5), false, this.conf);

    this.taskReportServer.start();

    // get the assigned address
    this.taskReportAddress = taskReportServer.getListenerAddress();
    this.conf.set("bsp.groom.report.address",
            taskReportAddress.getHostName() + ":" + taskReportAddress.getPort());
    LOG.info("TaskReportServer up at: " + this.taskReportAddress);

    this.groomHostName = rpcAddr;
    this.groomServerName = "groomd_" + this.rpcServer.replace(':', '_');
    LOG.info("Starting groom: " + this.rpcServer);

    // establish the communication link to bsp master
    this.masterClient = (MasterProtocol) RPC.waitForProxy(MasterProtocol.class,
            HamaRPCProtocolVersion.versionID, bspMasterAddr, conf);

    this.instructor = new Instructor();
    this.instructor.bind(DispatchTasksDirective.class, new DispatchTasksHandler());
    instructor.start();

    if (this.taskMonitorService == null) {
        this.taskMonitorService = Executors.newScheduledThreadPool(1);
        long monitorPeriod = this.conf.getLong(Constants.GROOM_PING_PERIOD,
                Constants.DEFAULT_GROOM_PING_PERIOD);
        if (monitorPeriod > 0) {
            this.taskMonitorService.scheduleWithFixedDelay(new BSPTasksMonitor(), 1000, monitorPeriod,
                    TimeUnit.MILLISECONDS);
        }
    }

    if (conf.getBoolean("bsp.monitor.enabled", false)) {
        new Monitor(conf, zk, this.groomServerName).start();
    }

    if (conf.getBoolean("bsp.monitor.fd.enabled", false)) {
        this.sensor.set(FDProvider.createSensor(
                conf.getClass("bsp.monitor.fd.sensor.class", UDPSensor.class, Sensor.class),
                (HamaConfiguration) conf));
        this.sensor.get().start();
    }

    // enroll in bsp master once the GroomServer is ready to accept tasks
    if (-1 == rpcPort || null == rpcAddr)
        throw new IllegalArgumentException("Error rpc address " + rpcAddr + " port" + rpcPort);
    if (!this.masterClient.register(new GroomServerStatus(groomServerName, cloneAndResetRunningTaskStatuses(),
            failures, maxCurrentTasks, this.rpcServer, groomHostName))) {
        LOG.error("There is a problem in establishing communication" + " link with BSPMaster");
        throw new IOException("There is a problem in establishing" + " communication link with BSPMaster.");
    }

    this.running = true;
    this.initialized = true;
}

From source file:org.openbmp.db_rest.resources.Orr.java

/**
 * Get IGP RIB with merged BGP RIB for given RouterId
 *
 * Merged BGP RIB will contain duplicate entries for selected BGP paths based
 *     on optimized next-hop selection and RR selection. For example:
 *
 *     prefix 10.0.0.0/8 is equal in attributes but has two possible next-hops
 *                  2.2.2.2 and 4.4.4.4, resulting tie breaker is IGP metric.
 *
 *        Local routerId IGP has metric 20 to 2.2.2.2 and metric 31 to 4.4.4.4
 *        RR IGP has metric 10 to 4.4.4.4 and 31 to 2.2.2.2.
 *
 *        Merged table would contain://from w  w  w . j  a v  a  2 s  .  c o  m
 *          10.0.0.0/8 via 2.2.2.2 metric 20 (metric 31 on rr) marked as preferred (orr selected)
 *          10.0.0.0/8 via 4.4.4.4 metric 31 (metric 10 on rr) marked as not preferred (rr selected w/o orr)
 *
 * NOTE:  The below method assumes (thus requires) that the bgp peer router
 *        advertising the link-state data is the route-reflector.  In other words,
 *        peerHashId (bgp peer hash) learned from bmp router_hash_id is the
 *        route-reflector.
 *
 *        We can change this to allow selection of BGP peers (one or more bmp routers)
 *        for the BGP RIB merge, but that requires more path/query params and is not needed right now.
 *
 *  @param peerHashId       Peer Hash ID of the BGP peer advertising link state information
 *  @param protocol         Either 'ospf' or 'isis'
 *  @param routerId         IPv4 or IPv6 print form router ID (use IPv4/IPv6 rid for ISIS)
 *  @param where            Advanced WHERE clause to filter the BGP merged prefixes
 */
@GET
@Path("/peer/{peerHashId}/{protocol}/{routerId}")
@Produces("application/json")
public Response getLsOspfIGP(@PathParam("peerHashId") String peerHashId, @PathParam("protocol") String protocol,
        @PathParam("routerId") String routerId, @QueryParam("where") String where) {

    long startTime = System.currentTimeMillis();

    ScheduledExecutorService thrPool = Executors.newScheduledThreadPool(2);
    queryThread thrs[] = new queryThread[2];

    // Get IGP for requested router
    thrs[0] = new queryThread(this);
    thrs[0].setArgs(new String[] { peerHashId, routerId, protocol, "30" });
    thrPool.schedule(thrs[0], 0, TimeUnit.MILLISECONDS);

    // Get the router's local router id
    // TODO: Change to support better identification of route reflector
    Map<String, List<DbColumnDef>> rrMap = getPeerRouterId(peerHashId);

    String rr_routerId = null;
    if (rrMap.size() > 0)
        rr_routerId = rrMap.entrySet().iterator().next().getValue().get(0).getValue();

    if (rr_routerId == null) {
        System.out.println("Unable to get the routers routerID by peer hash " + peerHashId);
        return RestResponse.okWithBody("{}");
    }

    // Get the RR IGP
    thrs[1] = new queryThread(this);
    thrs[1].setArgs(new String[] { peerHashId, rr_routerId, protocol, "120" });
    thrPool.schedule(thrs[1], 0, TimeUnit.MILLISECONDS);

    // Wait for IGP query and store the results
    waitForThread(thrs[0]);
    Map<String, List<DbColumnDef>> igpMap = thrs[0].getResults();

    if (igpMap.size() <= 0) {
        return RestResponse.okWithBody("{}");
    }

    // Get the BGP RIB from RR router
    List<DbColumnDef> row = igpMap.entrySet().iterator().next().getValue();
    String routerHashId = row.get(row.size() - 1).getValue();

    String where_str = "router_hash_id = '" + routerHashId + "'";

    if (where != null)
        where_str += " and " + where;

    StringBuilder query = new StringBuilder();
    query.append("SELECT Prefix as prefix,PrefixLen as prefix_len,LocalPref,ASPath_Count,Origin,MED,NH\n");
    query.append("     FROM v_routes WHERE ");
    query.append(where_str);
    query.append(" ORDER BY prefix_bin,PrefixLen LIMIT 1000\n");

    Map<String, List<DbColumnDef>> bgpMap = DbUtils.select_DbToMap(mysql_ds, query.toString());

    // Wait for RR IGP query and store the results
    waitForThread(thrs[1]);
    Map<String, List<DbColumnDef>> rr_igpMap = thrs[1].getResults();

    //long queryTime = System.currentTimeMillis() - startTime;

    thrPool.shutdownNow();

    /*
     * Merge BGP RIB into IGP
     */

    Map<String, List<DbColumnDef>> mergeMap = new HashMap<String, List<DbColumnDef>>();
    mergeMap.putAll(igpMap);

    mergeMap.putAll(mergeIgpWithBgp(igpMap, bgpMap, null, false));

    mergeMap.putAll(mergeIgpWithBgp(rr_igpMap, bgpMap, igpMap, true));

    long queryTime = System.currentTimeMillis() - startTime;

    return RestResponse.okWithBody(DbUtils.DbMapToJson("orr", mergeMap, queryTime));
}

From source file:nattable.DataGridNatTable.java

public void onStart() {
    Display.getDefault().asyncExec(new Runnable() {
        public void run() {
            scheduledThreadPool = Executors.newScheduledThreadPool(1);
            System.out.println("Starting data load.");
            scheduledThreadPool.schedule(new DataLoader(propertyChangeListener, baseEventList), 100L,
                    TimeUnit.MILLISECONDS);
            //scheduledThreadPool.scheduleAtFixedRate(new DataUpdater(bodyDataProvider), 100L, 5000L, TimeUnit.MILLISECONDS);
        }/*w w w.j a  v  a  2s  .  co m*/
    });
}

From source file:org.wso2.carbon.core.CarbonAxisConfigurator.java

@Override
protected void startSearch(RepositoryListener listener) {
    schedulerTask = new CarbonDeploymentSchedulerTask(listener, axisConfig,
            MultitenantConstants.SUPER_TENANT_ID, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    scheduler = Executors.newScheduledThreadPool(1);
    String deploymentInterval = CarbonCoreDataHolder.getInstance().getServerConfigurationService()
            .getFirstProperty("Axis2Config.DeploymentUpdateInterval");
    int deploymentIntervalInt = 15;
    if (deploymentInterval != null) {
        deploymentIntervalInt = Integer.parseInt(deploymentInterval);
    }/*from  w  ww. j a v  a2  s.c  o  m*/
    scheduler.scheduleWithFixedDelay(schedulerTask, 0, deploymentIntervalInt, TimeUnit.SECONDS);
}

From source file:services.travel.TravelService.java

public void checkForItvTimedDespawn(CreatureObject actor, SWGObject object) {

    Executors.newScheduledThreadPool(1).schedule(new Runnable() {
        public void run() {
            try {

                if (object != null) {
                    core.objectService.destroyObject(object);
                    actor.sendSystemMessage("@travel:pickup_timeout", DisplayType.Broadcast);
                    actor.setAttachment("itv", null);
                }/*w  ww  . j a v a  2  s .c o  m*/
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 30, TimeUnit.SECONDS);
}

From source file:org.wso2.carbon.core.multitenancy.TenantAxisConfigurator.java

@Override
protected void startSearch(RepositoryListener listener) {
    schedulerTask = new CarbonDeploymentSchedulerTask(listener, axisConfig, tenantId, tenantDomain);
    scheduler = Executors.newScheduledThreadPool(1);
    String deploymentInterval = CarbonCoreDataHolder.getInstance().getServerConfigurationService()
            .getFirstProperty("Axis2Config.DeploymentUpdateInterval");
    int deploymentIntervalInt = 15;
    if (deploymentInterval != null) {
        deploymentIntervalInt = Integer.parseInt(deploymentInterval);
    }/*from www. j  av a  2  s . co  m*/
    scheduler.scheduleWithFixedDelay(schedulerTask, 0, deploymentIntervalInt, TimeUnit.SECONDS);
}

From source file:org.fao.geonet.Geonetwork.java

/**
 * Sets up a periodic check whether GeoNetwork can successfully write to the database. If it can't, GeoNetwork will
 * automatically switch to read-only mode.
 *//*from ww w .  j  a v  a  2  s .  c  o m*/
private void createDBHeartBeat(final ResourceManager rm, final GeonetContext gc, Integer initialDelay,
        Integer fixedDelay) {
    logger.info("creating DB heartbeat with initial delay of " + initialDelay + " s and fixed delay of "
            + fixedDelay + " s");
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    Runnable DBHeartBeat = new Runnable() {
        private static final String INSERT = "INSERT INTO Settings(id, parentId, name, value) VALUES(?, ?, ?, ?)";
        private static final String REMOVE = "DELETE FROM Settings WHERE id=?";

        /**
         *
         */
        @Override
        public void run() {
            try {
                boolean readOnly = gc.isReadOnly();
                logger.debug("DBHeartBeat: GN is read-only ? " + readOnly);
                boolean canWrite = checkDBWrite();
                HarvestManager hm = gc.getHarvestManager();
                if (readOnly && canWrite) {
                    logger.warning("GeoNetwork can write to the database, switching to read-write mode");
                    readOnly = false;
                    gc.setReadOnly(readOnly);
                    hm.setReadOnly(readOnly);
                } else if (!readOnly && !canWrite) {
                    logger.warning("GeoNetwork can not write to the database, switching to read-only mode");
                    readOnly = true;
                    gc.setReadOnly(readOnly);
                    hm.setReadOnly(readOnly);
                } else {
                    if (readOnly) {
                        logger.info("GeoNetwork remains in read-only mode");
                    } else {
                        logger.debug("GeoNetwork remains in read-write mode");
                    }
                }
            }
            // any uncaught exception would cause the scheduled execution to silently stop
            catch (Throwable x) {
                logger.error("DBHeartBeat error: " + x.getMessage() + " This error is ignored.");
                x.printStackTrace();
            }
        }

        /**
         *
         * @return
         */
        private boolean checkDBWrite() {
            Dbms dbms = null;
            try {
                Integer testId = Integer.valueOf("100000");
                dbms = (Dbms) rm.openDirect(Geonet.Res.MAIN_DB);
                dbms.execute(INSERT, testId, Integer.valueOf("1"), "DBHeartBeat", "Yeah !");
                dbms.execute(REMOVE, testId);
                return true;
            } catch (Exception x) {
                logger.info("DBHeartBeat Exception: " + x.getMessage());
                return false;
            } finally {
                try {
                    if (dbms != null)
                        rm.close(Geonet.Res.MAIN_DB, dbms);
                } catch (Exception x) {
                    logger.error("DBHeartBeat failed to close DB connection. Your system is unstable! Error: "
                            + x.getMessage());
                    x.printStackTrace();
                }
            }
        }
    };
    scheduledExecutorService.scheduleWithFixedDelay(DBHeartBeat, initialDelay, fixedDelay, TimeUnit.SECONDS);
}

From source file:com.embeddedlog.LightUpDroid.LightUpPiSync.java

/**
 * Initiates a background thread to check if the LightUpPi server is reachable.
 *
 * @param guiHandler Handler for the activity GUI, for which to send one of the two runnables.
 * @param online Runnable to execute in the Handler if the server is online.
 * @param offline Runnable to execute in the Handler if the server is offline.
 *///from ww w .  j a v a  2s  .  c o m
public void startBackgroundServerCheck(final Handler guiHandler, final Runnable online,
        final Runnable offline) {
    // Check for network connectivity
    ConnectivityManager connMgr = (ConnectivityManager) mActivityContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if ((networkInfo != null) && networkInfo.isConnected()
            && ((scheduleServerCheck == null) || scheduleServerCheck.isShutdown())) {
        // Get the ping address
        final Uri.Builder pingUri = getServerUriBuilder();
        pingUri.appendPath("ping");
        // Schedule the background server check
        scheduleServerCheck = Executors.newScheduledThreadPool(1);
        scheduleServerCheck.scheduleWithFixedDelay(new Runnable() {
            public void run() {
                int response = 0;
                try {
                    URL url = new URL(pingUri.build().toString());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(3000); /* milliseconds */
                    conn.setConnectTimeout(5000); /* milliseconds */
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);
                    conn.connect();
                    response = conn.getResponseCode();
                } catch (Exception e) {
                    // Safely ignored as a response!=200 will trigger the offline title
                }
                if (response == 200) {
                    if (Log.LOGV)
                        Log.i(LOG_TAG + "Server response 200");
                    guiHandler.post(online);
                } else {
                    if (Log.LOGV)
                        Log.i(LOG_TAG + "Server response NOT 200");
                    guiHandler.post(offline);
                }
            }
        }, 0, 30, TimeUnit.SECONDS);
        if (Log.LOGV)
            Log.v(LOG_TAG + "BackgroundServerCheck started");
    } else {
        if (Log.LOGV)
            Log.d(LOG_TAG + "Server response NOT 200");
        guiHandler.post(offline);
    }
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * {@inheritDoc}//from  ww  w .java2 s.  c o m
 * 
 * @see org.osgi.service.cm.ManagedService#updated(java.util.Dictionary)
 */
@Override
@SuppressWarnings("rawtypes")
public void updated(Dictionary properties) throws ConfigurationException {
    String maxAttempts = StringUtils.trimToNull((String) properties.get(MAX_ATTEMPTS_CONFIG_KEY));
    if (maxAttempts != null) {
        try {
            maxAttemptsBeforeErrorState = Integer.parseInt(maxAttempts);
            logger.info("Set max attempts before error state to {}", maxAttempts);
        } catch (NumberFormatException e) {
            logger.warn("Can not set max attempts before error state to {}. {} must be an integer", maxAttempts,
                    MAX_ATTEMPTS_CONFIG_KEY);
        }
    }

    long dispatchInterval = DEFAULT_DISPATCH_INTERVAL;
    String dispatchIntervalString = StringUtils.trimToNull((String) properties.get(OPT_DISPATCHINTERVAL));
    if (StringUtils.isNotBlank(dispatchIntervalString)) {
        try {
            dispatchInterval = Long.parseLong(dispatchIntervalString);
        } catch (Exception e) {
            logger.warn("Dispatch interval '{}' is malformed, setting to {}", dispatchIntervalString,
                    MIN_DISPATCH_INTERVAL);
            dispatchInterval = MIN_DISPATCH_INTERVAL;
        }
        if (dispatchInterval == 0) {
            logger.info("Dispatching disabled");
        } else if (dispatchInterval < MIN_DISPATCH_INTERVAL) {
            logger.warn("Dispatch interval {} ms too low, adjusting to {}", dispatchInterval,
                    MIN_DISPATCH_INTERVAL);
            dispatchInterval = MIN_DISPATCH_INTERVAL;
        } else {
            logger.info("Dispatch interval set to {} ms", dispatchInterval);
        }
    }

    long heartbeatInterval = DEFAULT_HEART_BEAT;
    String heartbeatIntervalString = StringUtils.trimToNull((String) properties.get(OPT_HEARTBEATINTERVAL));
    if (StringUtils.isNotBlank(heartbeatIntervalString)) {
        try {
            heartbeatInterval = Long.parseLong(heartbeatIntervalString);
        } catch (Exception e) {
            logger.warn("Heartbeat interval '{}' is malformed, setting to {}", heartbeatIntervalString,
                    DEFAULT_HEART_BEAT);
            heartbeatInterval = DEFAULT_HEART_BEAT;
        }
        if (heartbeatInterval == 0) {
            logger.info("Heartbeat disabled");
        } else if (heartbeatInterval < 0) {
            logger.warn("Heartbeat interval {} minutes too low, adjusting to {}", heartbeatInterval,
                    DEFAULT_HEART_BEAT);
            heartbeatInterval = DEFAULT_HEART_BEAT;
        } else {
            logger.info("Dispatch interval set to {} minutes", heartbeatInterval);
        }
    }

    // Stop the current scheduled executors so we can configure new ones
    if (scheduledExecutor != null) {
        scheduledExecutor.shutdown();
        scheduledExecutor = Executors.newScheduledThreadPool(2);
    }

    // Schedule the service heartbeat if the interval is > 0
    if (heartbeatInterval > 0) {
        logger.debug("Starting service heartbeat at a custom interval of {}s", heartbeatInterval);
        scheduledExecutor.scheduleWithFixedDelay(new JobProducerHearbeat(), heartbeatInterval,
                heartbeatInterval, TimeUnit.SECONDS);
    }

    // Schedule the job dispatching.
    if (dispatchInterval > 0) {
        logger.debug("Starting job dispatching at a custom interval of {}s", DEFAULT_DISPATCH_INTERVAL / 1000);
        scheduledExecutor.scheduleWithFixedDelay(new JobDispatcher(), dispatchInterval, dispatchInterval,
                TimeUnit.MILLISECONDS);
    }
}

From source file:org.fao.geonet.OgpAppHandler.java

/**
 * Sets up a periodic check whether GeoNetwork can successfully write to the database. If it can't, GeoNetwork will
 * automatically switch to read-only mode.
 *///from www. ja v  a2 s.  c o  m
private void createDBHeartBeat(final GeonetContext gc, Integer initialDelay, Integer fixedDelay)
        throws SchedulerException {
    logger.info("creating DB heartbeat with initial delay of " + initialDelay + " s and fixed delay of "
            + fixedDelay + " s");
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    Runnable DBHeartBeat = new Runnable() {
        @Override
        public void run() {
            try {
                boolean readOnly = gc.isReadOnly();
                logger.debug("DBHeartBeat: GN is read-only ? " + readOnly);
                boolean canWrite = checkDBWrite();
                HarvestManager hm = gc.getBean(HarvestManager.class);
                if (readOnly && canWrite) {
                    logger.warning("GeoNetwork can write to the database, switching to read-write mode");
                    readOnly = false;
                    gc.setReadOnly(readOnly);
                    hm.setReadOnly(readOnly);
                } else if (!readOnly && !canWrite) {
                    logger.warning("GeoNetwork can not write to the database, switching to read-only mode");
                    readOnly = true;
                    gc.setReadOnly(readOnly);
                    hm.setReadOnly(readOnly);
                } else {
                    if (readOnly) {
                        logger.info("GeoNetwork remains in read-only mode");
                    } else {
                        logger.debug("GeoNetwork remains in read-write mode");
                    }
                }
            } catch (Throwable x) {
                // any uncaught exception would cause the scheduled execution to silently stop
                logger.error("DBHeartBeat error: " + x.getMessage() + " This error is ignored.");
                x.printStackTrace();
            }
        }

        private boolean checkDBWrite() {
            SettingRepository settingsRepo = gc.getBean(SettingRepository.class);
            try {
                Setting newSetting = settingsRepo.save(new Setting().setName("DBHeartBeat").setValue("value"));
                settingsRepo.flush();
                settingsRepo.delete(newSetting);
                return true;
            } catch (Exception x) {
                logger.info("DBHeartBeat Exception: " + x.getMessage());
                return false;
            }
        }
    };
    scheduledExecutorService.scheduleWithFixedDelay(DBHeartBeat, initialDelay, fixedDelay, TimeUnit.SECONDS);
}