Example usage for java.util Timer Timer

List of usage examples for java.util Timer Timer

Introduction

In this page you can find the example usage for java.util Timer Timer.

Prototype

public Timer() 

Source Link

Document

Creates a new timer.

Usage

From source file:com.frand.easyandroid.http.FFFileRespHandler.java

private void startTimer(final int reqTag, final String reqUrl) {
    timerInterrupt = false;//from w  w  w.  j  av a2s.  c o  m
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            while (!timerInterrupt) {
                sendProgressMsg(totalSize, getDownloadSize(), networkSpeed, reqTag, reqUrl);
                try {
                    Thread.sleep(TIMERSLEEPTIME);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }, 0, 1000);
    new Thread(new Runnable() {

        @Override
        public void run() {

        }
    }).start();
}

From source file:com.attentec.AttentecService.java

/**
 * Start recurring fetches of contacts and locations,
 * and also update our own location at intervals.
 *//*ww  w.ja  v a 2  s  . com*/
private void startService() {
    Log.d(TAG, "startService");
    //fetch the interval for getting contacts
    contactsUpdateInterval = PreferencesHelper.getContactsUpdateInterval(this);

    //set the time updated to server to a long time ago
    lastUpdatedToServer = new Date().getTime()
            - DevelopmentSettings.MILLISECONDS_IN_MINUTE * DevelopmentSettings.MINUTES_IN_DAY;

    //Display a notification about us starting.  We put an icon in the status bar.
    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    showNotification();

    //initialize database contact
    dbh = new DatabaseAdapter(this);
    dbh.open();
    //get contacts every contactsUpdateInterval
    contactsTimer = new Timer();
    contactsTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            getContacts();
        }
    }, 0, contactsUpdateInterval);

    locationTimer = new Timer();
    locationTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            //get others locations
            getLocations();
        }
    }, 0, PreferencesHelper.getLocationsUpdateInterval(ctx));

    ownLocationTimer = new Timer();
    ownLocationTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if (PreferencesHelper.getLocationUpdateEnabled(ctx)) {
                //get own location
                locationHelper.getLocation(ctx, locationResult);
                //check if we need to update the notification
            }
            updateNotificationIfNeeded();
        }
    }, 0, PreferencesHelper.getLocationsUpdateOwnInterval(ctx));

    isAlive = true;
    Intent serviceStartedIntent = new Intent(COM_ATTENTEC_SERVICE_CHANGED_STATUS);
    sendBroadcast(serviceStartedIntent);
}

From source file:com.gsma.mobileconnect.utils.RestClient.java

/**
 * Execute the given request./*from  w  ww.  ja  v  a2s  .  c om*/
 * <p>
 * Abort the request if it exceeds the specified timeout.
 *
 * @param httpClient The client to use.
 * @param request The request to make.
 * @param context The context to use.
 * @param timeout The timeout to use.
 * @return A Http Response.
 * @throws RestException Thrown if the request fails or times out.
 */
private CloseableHttpResponse executeRequest(CloseableHttpClient httpClient, final HttpRequestBase request,
        HttpClientContext context, int timeout) throws RestException {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            request.abort();
        }
    }, timeout);

    RequestConfig localConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout)
            .setConnectTimeout(timeout).setSocketTimeout(timeout).setCookieSpec(CookieSpecs.STANDARD).build();
    request.setConfig(localConfig);
    try {
        return httpClient.execute(request, context);
    } catch (IOException ex) {
        String requestUri = request.getURI().toString();
        if (request.isAborted()) {
            throw new RestException("Rest end point did not respond", requestUri);
        }
        throw new RestException("Rest call failed", requestUri, ex);
    }
}

From source file:hsa.awp.scire.controller.ScireController.java

/**
 * Starts the timer if it is currently running.
 *///w ww  . j  a  v a  2s . c o m
@Override
public synchronized void startTimer() {

    if (timerIsRunning) {
        throw new IllegalStateException("timer is already running.");
    }
    logger.debug("starting timer");

    lastCheck = Calendar.getInstance();
    lastCheck.add(Calendar.YEAR, -30);

    timer = new Timer();
    timer.scheduleAtFixedRate(timerTaskFactory.getTask(new Runnable() {
        @Override
        public void run() {
            // TODO remove that one!!!
            SecurityContextHolder.getContext()
                    .setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password"));
            try {
                check();
            } catch (Throwable e) {
                logger.error(e.toString(), e);
            }
        }
    }), 0, checkInterval);
    timerIsRunning = true;
}

From source file:com.firefly.sample.castcompanionlibrary.cast.player.VideoCastControllerFragment.java

private void handleMediaAuthTask(final IMediaAuthService authService) {
    mCastController.showLoading(true);/*w  ww . j  a v  a2  s. c  o  m*/
    mCastController.setLine2(null != authService.getPendingMessage() ? authService.getPendingMessage() : "");
    mAuthThread = new Thread(new Runnable() {

        @Override
        public void run() {
            if (null != authService) {
                try {
                    authService.setOnResult(VideoCastControllerFragment.this);
                    authService.start();
                } catch (Exception e) {
                    LOGE(TAG, "mAuthService.start() encountered exception", e);
                    mAuthSuccess = false;
                }
            }
        }
    });
    mAuthThread.start();

    // start a timeout timer; we don't want authorization process to take too long
    mMediaAuthTimer = new Timer();
    mMediaAuthTimer.schedule(new MediaAuthServiceTimerTask(mAuthThread), authService.getTimeout());
}

From source file:de.ufinke.cubaja.sort.SortManager.java

private void initTimer(final Log logger, final String prefix, final String key, final AtomicLong counter) {

    TimerTask task = new TimerTask() {

        public void run() {

            logger.trace(prefix + text.get(key, counter.get()));
        }//from w  w  w. j av  a  2 s  . c o  m
    };

    timer = new Timer();
    timer.schedule(task, logInterval, logInterval);
}

From source file:com.librelio.activity.StartupActivity.java

protected void onStartMagazine(int delay) {
    mStartupAdsTimer = new Timer();
    mStartupAdsTimer.schedule(new TimerTask() {
        @Override/*w  w  w .  j av a2 s. c o m*/
        public void run() {
            if (!advertisingClickPerformed) {
                startMainMagazineActivity();
            }
        }
    }, delay);
}

From source file:bamboo.trove.common.WarcProgressManager.java

private void setTick() {
    if (timer == null) {
        timer = new Timer();
    }//from w  w  w .  j a  v a 2 s.  c o m
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            checkQueues();
        }
    }, POLL_INTERVAL_SECONDS * 1000);
}

From source file:edu.ku.brc.specify.utilapps.ERDVisualizer.java

public ERDVisualizer() {
    boolean showTreeHierarchy = false;

    Locale.setDefault(currLang);/* w  w w  .  ja v a 2s  .  com*/
    UIRegistry.setResourceLocale(currLang);

    Vector<DBTableInfo> tables = DBTableIdMgr.getInstance().getTables();
    Collections.sort(tables);

    SchemaLocalizerXMLHelper schemaXMLHelper = new SchemaLocalizerXMLHelper(SpLocaleContainer.CORE_SCHEMA,
            DBTableIdMgr.getInstance());
    schemaXMLHelper.load(true);
    schemaXMLHelper.setTitlesIntoSchema();

    ERDTable.setDisplayType(showTreeHierarchy ? ERDTable.DisplayType.Title : ERDTable.DisplayType.All);

    tblTracker = new TableTracker();

    String schemDirName = adjustFileNameForLocale("schema%s");

    final File localSchemaDir = new File(schemDirName);
    if (!localSchemaDir.exists()) {
        localSchemaDir.mkdir();
    } else {
        try {
            FileUtils.cleanDirectory(localSchemaDir);

        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, ex);
            ex.printStackTrace();
        }
    }

    this.schemaDir = localSchemaDir;

    JPanel p = new JPanel(new BorderLayout());
    p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    p.add(mainPanel = new ERDPanel(tblTracker), BorderLayout.CENTER);
    setContentPane(new JScrollPane(p));
    p.setBackground(Color.WHITE);
    mainPanel.setBackground(Color.WHITE);

    try {
        File templateFile = new File(
                UIRegistry.getDefaultWorkingPath() + File.separator + "site/template.html");
        mapTemplate = FileUtils.readFileToString(templateFile);

    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, ex);
        ex.printStackTrace();
    }

    if (StringUtils.isEmpty(mapTemplate)) {
        System.err.println("The template file is empty!");
    }

    try {
        File srcDir = new File(UIRegistry.getDefaultWorkingPath() + File.separator + "site");
        for (File f : srcDir.listFiles()) {
            if (!f.getName().startsWith(".")) {
                File dst = new File(UIRegistry.getDefaultWorkingPath() + File.separator + schemDirName
                        + File.separator + f.getName());
                if (!FilenameUtils.getExtension(f.getName()).toLowerCase().equals("html")) {
                    FileUtils.copyFile(f, dst);
                }
            }
        }
    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, ex);
        ex.printStackTrace();
    }

    // Choose what to display

    if (!showTreeHierarchy) {
        advance();

        int period = isDoShadow() ? 10000 : 1000;
        int delay = isDoShadow() ? 5000 : 1000;
        timer = new Timer();

        if (true)

        {
            timer.scheduleAtFixedRate(new TimerTask() {
                public void run() {
                    advance();
                }
            }, period, delay);
        }
    } else {
        ERDTable.setDisplayType(ERDTable.DisplayType.Title);

        //this.tblTracker.setFont(this.tblTracker.getFont().deriveFont((float)10.0));
        ERDTable root = null;

        boolean doCollectionSchema = true;

        if (doCollectionSchema) {
            root = tblTracker.getTable("Discipline");

            //                                                skip,  processKids, alwaysAKid, processAnyRel, okWhenParent
            tblTracker.addNodeInfo("Agent", false, true, true, false, null);
            tblTracker.addNodeInfo("Determination", false, true, true, true, null);
            tblTracker.addNodeInfo("ConservDescription", false, true, true, true, null);

            tblTracker.addNodeInfo("Attachment", true, true, true, false, null);
            tblTracker.addNodeInfo("AttributeDef", true, true, true, false, null);
            tblTracker.addNodeInfo("SpAppResourceDir", true, true, true, false, null);
            tblTracker.addNodeInfo("SpLocaleContainer", true, true, true, false, null);
            tblTracker.addNodeInfo("DeaccessionPreparation", true, true, true, false, null);
            tblTracker.addNodeInfo("OtherIdentifier", true, true, true, false, null);
            tblTracker.addNodeInfo("CollectionRelationship", true, true, true, false, null);
            tblTracker.addNodeInfo("ProjectCollectionObject", true, true, true, false, null);
            tblTracker.addNodeInfo("CollectionObjectAttr", true, true, true, false, null);
            tblTracker.addNodeInfo("CollectionObjectAttachment", true, true, true, false, null);
            tblTracker.addNodeInfo("ConservDescriptionAttachment", true, true, true, false, null);
            tblTracker.addNodeInfo("ConservEventAttachment", true, true, true, false, null);

            // No Kids
            tblTracker.addNodeInfo("Discipline", false, false, true, false, null);
            tblTracker.addNodeInfo("Collection", false, false, true, false, null);
            tblTracker.addNodeInfo("Taxon", false, false, true, false, null);
            tblTracker.addNodeInfo("TaxonCitation", false, false, true, false, null);
            //                tblTracker.addNodeInfo("DeterminationCitation",  false, false, true,  false, null);
            tblTracker.addNodeInfo("ReferenceWork", false, false, true, false, null);
            tblTracker.addNodeInfo("Journal", false, false, true, false, null);
            tblTracker.addNodeInfo("CollectingEvent", false, false, true, false, null);
            tblTracker.addNodeInfo("Locality", false, false, true, false, null);
            tblTracker.addNodeInfo("Geography", false, false, true, false, null);
            tblTracker.addNodeInfo("PaleoContext", false, false, true, false, null);
            tblTracker.addNodeInfo("LithoStrat", false, false, true, false, null);
            tblTracker.addNodeInfo("GeologicTimePeriod", false, false, true, false, null);
            tblTracker.addNodeInfo("CollectionObjectCitation", false, false, true, false, null);
            tblTracker.addNodeInfo("Accession", false, false, true, false, null);
            tblTracker.addNodeInfo("AccessionAuthorization", false, false, true, false, null);
            tblTracker.addNodeInfo("AccessionAgent", false, false, true, false, null);
            tblTracker.addNodeInfo("Agent", false, false, true, false, null);
            tblTracker.addNodeInfo("Preparation", false, false, true, false, null);
            tblTracker.addNodeInfo("PrepType", false, false, true, false, null);
            tblTracker.addNodeInfo("RepositoryAgreement", false, false, true, false, null);
            tblTracker.addNodeInfo("ConservEvent", false, false, true, false, null);

            tblTracker.addNodeInfo("DNASequence", false, false, true, false, null);
            tblTracker.addNodeInfo("TreatmentEvent", false, false, true, false, null);
            tblTracker.addNodeInfo("Ipm", false, false, true, false, null);
            tblTracker.addNodeInfo("FieldNotebook", false, false, true, false, null);
            tblTracker.addNodeInfo("FieldNotebookPageSet", false, false, true, false, null);
            tblTracker.addNodeInfo("FieldNotebookPage", false, false, true, false, null);

            NodeInfo det = tblTracker.getNodeInfo("Determination");
            det.addKid(tblTracker.getTable("Taxon"));
            //                det.addKid(tblTracker.getTable("DeterminationStatus"));

            NodeInfo ni = tblTracker.getNodeInfo("Taxon");
            ni.addKid(tblTracker.getTable("TaxonCitation"));

            ni = tblTracker.getNodeInfo("Discipline");
            ni.addKid(tblTracker.getTable("Collection"));

            ni = tblTracker.getNodeInfo("Collection");
            ni.addKid(tblTracker.getTable("FieldNotebook"));
            ni.addKid(tblTracker.getTable("CollectionObject"));

            ni = tblTracker.getNodeInfo("CollectionObjectCitation");
            ni.addKid(tblTracker.getTable("ReferenceWork"));

            ni = tblTracker.getNodeInfo("TaxonCitation");
            ni.addKid(tblTracker.getTable("ReferenceWork"));

            ni = tblTracker.getNodeInfo("ReferenceWork");
            ni.setOkToDuplicate(true);
            ni.addKid(tblTracker.getTable("Journal"));

            ni = tblTracker.getNodeInfo("GeologicTimePeriod");
            ni.setOkToDuplicate(true);

            ni = tblTracker.getNodeInfo("Journal");
            ni.setOkToDuplicate(true);

            ni = tblTracker.getNodeInfo("CollectingEvent");
            ni.addKid(tblTracker.getTable("Locality"));

            ni = tblTracker.getNodeInfo("CollectionObject");
            ni.addKid(tblTracker.getTable("CollectingEvent"));
            ni.addKid(tblTracker.getTable("PaleoContext"));
            ni.addKid(tblTracker.getTable("Accession"));
            ni.addKid(tblTracker.getTable("DNASequence"));
            ni.addKid(tblTracker.getTable("TreatmentEvent"));
            ni.addKid(tblTracker.getTable("Ipm"));

            ni = tblTracker.getNodeInfo("Locality");
            ni.addKid(tblTracker.getTable("Geography"));

            ni = tblTracker.getNodeInfo("PaleoContext");
            ni.addKid(tblTracker.getTable("LithoStrat"));
            ni.addKid(tblTracker.getTable("GeologicTimePeriod"));

            ni = tblTracker.getNodeInfo("DeterminationCitation");
            ni.addKid(tblTracker.getTable("ReferenceWork"));

            ni = tblTracker.getNodeInfo("Preparation");
            ni.addKid(tblTracker.getTable("PrepType"));

            ni = tblTracker.getNodeInfo("Accession");
            ni.addKid(tblTracker.getTable("AccessionAuthorization"));
            ni.addKid(tblTracker.getTable("AccessionAgent"));
            ni.addKid(tblTracker.getTable("RepositoryAgreement"));
            //ni.addKid(tblTracker.getTable("Attachment"));
            //protected RepositoryAgreement repositoryAgreement;

            ni = tblTracker.getNodeInfo("ConservEvent");
            ni.addKid(tblTracker.getTable("ConservRecommendation"));

            ni = tblTracker.getNodeInfo("FieldNotebook");
            ni.addKid(tblTracker.getTable("FieldNotebookPageSet"));

            ni = tblTracker.getNodeInfo("FieldNotebookPageSet");
            ni.addKid(tblTracker.getTable("FieldNotebookPage"));

        } else {
            root = tblTracker.getTable("SpAppResourceDir");

            //                                           skip,  processKids, alwaysAKid, processAnyRel, okWhenParent
            //tblTracker.addNodeInfo("Agent",              false, true,        true,       false,         null);

            // No Kids
            tblTracker.addNodeInfo("SpAppResourceData", false, false, true, false, null);
            tblTracker.addNodeInfo("Collection", false, false, true, false, null);
            tblTracker.addNodeInfo("Discipline", false, false, true, false, null);
            tblTracker.addNodeInfo("SpecifyUser", false, false, true, false, null);
            tblTracker.addNodeInfo("SpAppResource", false, false, true, false, null);
            tblTracker.addNodeInfo("SpViewSetObj", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUIViewSet", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUIView", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUIViewDef", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUIAltView", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUIColumn", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUIRow", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUICell", false, false, true, false, null);

            NodeInfo ni = tblTracker.getNodeInfo("SpAppResourceDir");
            ni.addKid(tblTracker.getTable("SpAppResource"));
            ni.addKid(tblTracker.getTable("SpViewSetObj"));
            //ni.addKid(tblTracker.getTable("Collection"));
            //ni.addKid(tblTracker.getTable("Discipline"));
            //ni.addKid(tblTracker.getTable("SpecifyUser"));

            ni = tblTracker.getNodeInfo("SpAppResource");
            ni.addKid(tblTracker.getTable("SpAppResourceData"));

            ni = tblTracker.getNodeInfo("SpViewSetObj");
            ni.addKid(tblTracker.getTable("SpAppResourceData"));
            ni.addKid(tblTracker.getTable("SpUIViewSet"));

            ni = tblTracker.getNodeInfo("SpUIViewSet");
            ni.addKid(tblTracker.getTable("SpUIView"));
            ni.addKid(tblTracker.getTable("SpUIViewDef"));

            ni = tblTracker.getNodeInfo("SpUIView");
            ni.addKid(tblTracker.getTable("SpUIAltView"));

            ni = tblTracker.getNodeInfo("SpUIViewDef");
            ni.addKid(tblTracker.getTable("SpUIColumn"));
            ni.addKid(tblTracker.getTable("SpUIRow"));

            ni = tblTracker.getNodeInfo("SpUIRow");
            ni.addKid(tblTracker.getTable("SpUICell"));
            //ni.addKid(tblTracker.getTable("SpUIViewDef"));

            //ni = tblTracker.getNodeInfo("SpUIAltView");
            //ni.addKid(tblTracker.getTable("SpUIView"));
            //ni.addKid(tblTracker.getTable("SpUIViewDef"));

            ni = tblTracker.getNodeInfo("SpAppResourceData");
            ni.setOkToDuplicate(true);

            if (false) {
                NodeInfo det = tblTracker.getNodeInfo("Determination");
                det.addKid(tblTracker.getTable("Taxon"));
                //                    det.addKid(tblTracker.getTable("DeterminationStatus"));

                ni = tblTracker.getNodeInfo("Taxon");
                ni.addKid(tblTracker.getTable("TaxonCitation"));

                ni = tblTracker.getNodeInfo("CollectionObjectCitation");
                ni.addKid(tblTracker.getTable("ReferenceWork"));

                ni = tblTracker.getNodeInfo("TaxonCitation");
                ni.addKid(tblTracker.getTable("ReferenceWork"));

                ni = tblTracker.getNodeInfo("ReferenceWork");
                ni.setOkToDuplicate(true);
                ni.addKid(tblTracker.getTable("Journal"));

                ni = tblTracker.getNodeInfo("GeologicTimePeriod");
                ni.setOkToDuplicate(true);

                ni = tblTracker.getNodeInfo("Journal");
                ni.setOkToDuplicate(true);

                ni = tblTracker.getNodeInfo("CollectingEvent");
                ni.addKid(tblTracker.getTable("Locality"));

                ni = tblTracker.getNodeInfo("CollectionObject");
                ni.addKid(tblTracker.getTable("CollectingEvent"));
                ni.addKid(tblTracker.getTable("PaleoContext"));
                ni.addKid(tblTracker.getTable("Accession"));

                ni = tblTracker.getNodeInfo("Locality");
                ni.addKid(tblTracker.getTable("Geography"));

                ni = tblTracker.getNodeInfo("PaleoContext");
                ni.addKid(tblTracker.getTable("LithoStrat"));
                ni.addKid(tblTracker.getTable("GeologicTimePeriod"));

                ni = tblTracker.getNodeInfo("DeterminationCitation");
                ni.addKid(tblTracker.getTable("ReferenceWork"));

                ni = tblTracker.getNodeInfo("Preparation");
                ni.addKid(tblTracker.getTable("PrepType"));

                ni = tblTracker.getNodeInfo("Accession");
                ni.addKid(tblTracker.getTable("AccessionAuthorization"));
                ni.addKid(tblTracker.getTable("AccessionAgent"));
                ni.addKid(tblTracker.getTable("RepositoryAgreement"));
            }

        }

        if (false) {
            NodeInfo ni = tblTracker.getNodeInfo("Agent");
            ni.setOkToDuplicate(true);

            String[] toAddAgent = { "CollectionObject", "Accession", "Determination", "Preparation", };
            for (String name : toAddAgent) {
                ni = tblTracker.getNodeInfo(name);
                ni.addKid(tblTracker.getTable("Agent"));
            }
        }

        processAsTree(root, 0);
        mainPanel.addTree(root);

        final SwingWorker worker = new SwingWorker() {
            public Object construct() {
                try {
                    Thread.sleep(3000);

                } catch (Exception ex) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, ex);
                    ex.printStackTrace();
                }
                return null;
            }

            //Runs on the event-dispatching thread.
            public void finished() {
                generate();
                System.out.println("Done.");
            }
        };
        worker.start();
    }

    createIndexFile();
}

From source file:gov.nrel.bacnet.consumer.BACnet.java

private void initialize(Config config) throws IOException {
    LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(1000);
    RejectedExecutionHandler rejectedExec = new RejectedExecHandler();
    // schedule polling on single threaded service because local device instance is not threadsafe
    execSvc = Executors.newFixedThreadPool(config.getNumThreads());
    //give databus recording 2 threads to match old code
    recorderSvc = new ThreadPoolExecutor(20, 20, 120, TimeUnit.SECONDS, queue, rejectedExec);
    schedSvc = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(config.getNumThreads());
    exec = new OurExecutor(schedSvc, execSvc, recorderSvc);
    String devname = config.getNetworkDevice();
    int device_id = config.getDeviceId();
    NetworkInterface networkinterface = null;

    try {/* w  w w  .  j  a v  a 2 s .  c  o m*/
        networkinterface = java.net.NetworkInterface.getByName(devname);
    } catch (Exception ex) {
        System.out.println("Unable to open device: " + devname);
        System.exit(-1);
    }

    if (networkinterface == null) {
        System.out.println("Unable to open device: " + devname);
        System.exit(-1);
    }

    List<InterfaceAddress> addresses = networkinterface.getInterfaceAddresses();

    String sbroadcast = null;
    String saddress = null;
    //InterfaceAddress ifaceaddr = null;

    for (InterfaceAddress address : addresses) {
        logger.fine("Evaluating address: " + address.toString());
        if (address.getAddress().getAddress().length == 4) {
            logger.info("Address is ipv4, selecting: " + address.toString());
            sbroadcast = address.getBroadcast().toString().substring(1);
            saddress = address.getAddress().toString().substring(1);
            //ifaceaddr = address;
            break;
        } else {
            logger.info("Address is not ipv4, not selecting: " + address.toString());
        }
    }

    logger.info("Binding to: " + saddress + " " + sbroadcast);

    localDevice = new LocalDevice(device_id, sbroadcast);
    localDevice.setPort(LocalDevice.DEFAULT_PORT);
    localDevice.setTimeout(localDevice.getTimeout() * 3);
    localDevice.setSegTimeout(localDevice.getSegTimeout() * 3);
    try {
        localDevice.initialize();
        localDevice.setRetries(0); //don't retry as it seems to really be a waste.
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    if (config.getSlaveDeviceEnabled()) {
        slaveDeviceTimer = new Timer();
        slaveDeviceTimer.schedule(new gov.nrel.bacnet.SlaveDevice(localDevice, config), 1000,
                config.getSlaveDeviceUpdateInterval() * 1000);
    }

    int counter = 0;

    String username = config.getDatabusUserName();
    String key = config.getDatabusKey();

    logger.info("user=" + username + " key=" + key);

    DatabusSender sender = null;

    if (config.getDatabusEnabled()) {
        sender = new DatabusSender(username, key, execSvc, config.getDatabusUrl(), config.getDatabusPort(),
                true);
    }
    logger.info("databus sender: " + sender);
    writer = new DatabusDataWriter(new DataPointWriter(sender));
    logger.info("databus writer" + writer);
}