Example usage for java.util Timer schedule

List of usage examples for java.util Timer schedule

Introduction

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

Prototype

public void schedule(TimerTask task, Date firstTime, long period) 

Source Link

Document

Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.

Usage

From source file:Main.java

public static Timer setInterval(final Runnable runnable, int delayMillis, int period) {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override/*  ww w .  ja va  2  s .  co m*/
        public void run() {
            handler.post(runnable);
        }
    }, delayMillis, period);
    return timer;
}

From source file:org.ehcache.myapp.Main.java

public static void checkUpdates() {
    Timer timer = new Timer();
    timer.schedule(new Updater(), 1000, 120 * 1000);
}

From source file:Main.java

public static void startTimer(TimerTask task, long interval) {
    final long IMMEDIATELY = 0;

    Timer timer = new Timer(true);
    timer.schedule(task, IMMEDIATELY, interval);
}

From source file:com.ligadata.kamanja.consumer.Main.java

private static void startScheduledTasks() {

        Calendar alertsAggCal = Calendar.getInstance();
        alertsAggCal.add(Calendar.MILLISECOND, START_SCHEDULED_TASK_AFTER);

        Timer timer = new Timer();
        timer.schedule(new AlertsAggTimerTask(), alertsAggCal.getTime(),
                config.getLong(ConfigFields.ALERTS_AGG_TASK_PERIOD_MILLIES));

    }/*from   ww  w  .  jav  a  2 s  .c om*/

From source file:net.vicp.lylab.util.timer.LYPlan.java

public static void BeginSchedule(LYPlan plan) {
    if (Scheduled)
        return;/*  www. jav  a 2s .co m*/
    else
        Scheduled = true;
    Timer timer = new Timer();
    for (TimerJob bj : plan.getJobs()) {
        if (bj.getInterval() != 0)
            timer.schedule(bj, bj.getStartTime(), bj.getInterval());
        else
            timer.schedule(bj, bj.getStartTime());
        System.out.println("LYPlan - Load Schedule Job: " + bj.getClass().getName());
    }
}

From source file:dk.netarkivet.wayback.indexer.WaybackIndexer.java

/**
 * Starts the producer thread. This thread runs on a timer. It downloads a list of all files in the archive and adds
 * any new ones to the database. It then checks the database for unindexed files and adds them to the queue.
 *//* w ww  .j a  va2s .  c om*/
private static void startProducerThread() {
    Long producerDelay = Settings.getLong(WaybackSettings.WAYBACK_INDEXER_PRODUCER_DELAY);
    Long producerInterval = Settings.getLong(WaybackSettings.WAYBACK_INDEXER_PRODUCER_INTERVAL);
    Long recentProducerInterval = Settings.getLong(WaybackSettings.WAYBACK_INDEXER_RECENT_PRODUCER_INTERVAL);
    TimerTask completeProducerTask = new TimerTask() {
        @Override
        public void run() {
            log.info("Starting producer task for all filenames");
            IndexerQueue iq = IndexerQueue.getInstance();
            iq.populate();
            FileNameHarvester.harvestAllFilenames();
            iq.populate();
        }
    };
    Timer producerThreadTimer = new Timer("ProducerThread");
    producerThreadTimer.schedule(completeProducerTask, producerDelay, producerInterval);
    TimerTask recentProducerTask = new TimerTask() {
        @Override
        public void run() {
            log.info("Starting producer task for recent files");
            IndexerQueue iq = IndexerQueue.getInstance();
            iq.populate();
            FileNameHarvester.harvestRecentFilenames();
            iq.populate();
        }
    };
    producerThreadTimer.schedule(recentProducerTask, producerDelay, recentProducerInterval);
}

From source file:io.trivium.Central.java

public static void start() {

    //register activities
    Registry.INSTANCE.reload();//from  w w w  .j a v  a  2s  .  co m

    try {
        //init ui handler
        Binding b = Registry.INSTANCE.getBinding(TypeRef.getInstance(WebUI.class.getCanonicalName()));
        b.startBinding();
        //init web object handler
        b = Registry.INSTANCE.getBinding(TypeRef.getInstance(WebObjectHandler.class.getCanonicalName()));
        b.startBinding();
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "error initializing the builtin http handler", ex);
    }
    //start anystore server
    Thread td = new Thread(AnyServer.INSTANCE, "anystore");
    td.setDaemon(true);
    td.start();

    // init profiler
    Timer t = new Timer();
    //one second after next time frame starts
    long start = TimeUtils.getTimeFrameStart(new Date().getTime() + 60000);
    t.schedule(Profiler.INSTANCE, new Date(start), 60000);

    logger.log(Level.INFO,
            "trivium is now running and accessible through the web interface on http://localhost:12345/ui/");
}

From source file:org.openhab.binding.knx.internal.connection.KNXConnection.java

/**
 * Tries to connect either by IP or serial bus, depending on supplied config data.
 * @return true if connection was established, false otherwise
 *///from  w w w.  ja v a  2  s .c  o m
public static synchronized boolean connect() {
    boolean successRetVal = false;

    sShutdown = false;
    try {
        if (StringUtils.isNotBlank(sIp)) {
            sLink = connectByIp(sIpConnectionType, sLocalIp, sIp, sPort);
        } else if (StringUtils.isNotBlank(sSerialPort)) {
            sLink = connectBySerial(sSerialPort);
        } else {
            sLogger.error("No IP address or serial port could be found in configuration!");
            return false;
        }

        NetworkLinkListener linkListener = new NetworkLinkListener() {
            public void linkClosed(CloseEvent e) {
                if (!(CloseEvent.USER_REQUEST == e.getInitiator()) && !sShutdown) {
                    sLogger.warn("KNX link has been lost (reason: {} on object {})", e.getReason(),
                            e.getSource().toString());
                    for (KNXConnectionListener listener : KNXConnection.sConnectionListeners) {
                        listener.connectionLost();
                    }

                    /*
                     * If an auto reconnect period was scheduled, then start a timer based task, which will
                     * try to reconnect.
                     */

                    if (sAutoReconnectPeriod > 0) {
                        sLogger.info("KNX link will be retried in " + sAutoReconnectPeriod + " seconds");
                        final Timer timer = new Timer();
                        TimerTask timerTask = new ConnectTimerTask(timer);
                        timer.schedule(timerTask, sAutoReconnectPeriod * 1000, sAutoReconnectPeriod * 1000);
                    }
                }
            }

            public void indication(FrameEvent e) {
            }

            public void confirmation(FrameEvent e) {
            }
        };

        sLink.addLinkListener(linkListener);

        if (sPC != null) {
            sPC.removeProcessListener(sProcessCommunicationListener);
            sPC.detach();
        }

        sPC = new ProcessCommunicatorImpl(sLink);
        sPC.setResponseTimeout((int) sResponseTimeout / 1000);

        if (sProcessCommunicationListener != null) {
            sPC.addProcessListener(sProcessCommunicationListener);
        }

        if (sLogger.isInfoEnabled()) {
            if (sLink instanceof KNXNetworkLinkIP) {
                String ipConnectionTypeString = KNXConnection.sIpConnectionType == KNXNetworkLinkIP.ROUTING
                        ? "ROUTER"
                        : "TUNNEL";
                sLogger.info("Established connection to KNX bus on {} in mode {}.", sIp + ":" + sPort,
                        ipConnectionTypeString);
            } else {
                sLogger.info("Established connection to KNX bus through FT1.2 on serial port {}.", sSerialPort);
            }
        }

        for (KNXConnectionListener listener : KNXConnection.sConnectionListeners) {
            listener.connectionEstablished();
        }

        successRetVal = true;

    } catch (KNXException e) {
        sLogger.error("Error connecting to KNX bus: {}", e.getMessage());
    } catch (UnknownHostException e) {
        sLogger.error("Error connecting to KNX bus (unknown host): {}", e.getMessage());
    } catch (InterruptedException e) {
        sLogger.error("Error connecting to KNX bus (interrupted): {}", e.getMessage());
    }
    return successRetVal;
}

From source file:org.wattdepot.client.http.api.collector.MultiThreadedCollector.java

/**
 * @param serverUri The URI for the WattDepot server.
 * @param username The name of a user defined in the WattDepot server.
 * @param orgId the user's organization id.
 * @param password The password for the user.
 * @param collectorId The CollectorProcessDefinitionId used to initialize this
 *        collector./*  w w w.j  a  v  a 2  s . c  o m*/
 * @param debug flag for debugging messages.
 * @return true if sensor starts successfully.
 * @throws InterruptedException If sleep is interrupted for some reason.
 * @throws BadCredentialException if the username and password are invalid.
 */
public static boolean start(String serverUri, String username, String orgId, String password,
        String collectorId, boolean debug) throws InterruptedException, BadCredentialException {

    // Before starting any sensors, confirm that we can connect to the WattDepot
    // server. We do
    // this here because if the server and sensors are running on the same
    // system, at boot time the
    // sensor might start before the server, causing client calls to fail. If
    // this happens, we
    // want to catch it at the top level, where it will result in the sensor
    // process terminating.
    // If we wait to catch it at the per-sensor level, it might cause a sensor
    // to abort for what
    // might be a short-lived problem. The sensor process should be managed by
    // some other process
    // (such as launchd), so it is OK to terminate because it should get
    // restarted if the server
    // isn't up quite yet.
    WattDepotClient staticClient = new WattDepotClient(serverUri, username, orgId, password);
    if (!staticClient.isHealthy()) {
        System.err.format("Could not connect to server %s. Aborting.%n", serverUri);
        // Pause briefly to rate limit restarts if server doesn't come up for a
        // long time
        Thread.sleep(2000);
        return false;
    }
    // Get the collector process definition
    CollectorProcessDefinition definition = null;
    Sensor sensor = null;
    SensorModel model = null;

    try {
        definition = staticClient.getCollectorProcessDefinition(collectorId);
        staticClient.getDepository(definition.getDepositoryId());
        sensor = staticClient.getSensor(definition.getSensorId());
        model = staticClient.getSensorModel(sensor.getModelId());
        // Get SensorModel to determine what type of collector to start.
        if (model.getName().equals(SensorModelHelper.EGAUGE) && model.getVersion().equals("1.0")) {
            Timer t = new Timer();
            try {
                EGaugeCollector collector = new EGaugeCollector(serverUri, username, sensor.getOrganizationId(),
                        password, collectorId, debug);
                if (collector.isValid()) {
                    System.out.format("Started polling %s sensor at %s%n", sensor.getName(),
                            Tstamp.makeTimestamp());
                    t.schedule(collector, 0, definition.getPollingInterval() * 1000);
                } else {
                    System.err.format("Cannot poll %s sensor%n", sensor.getName());
                    return false;
                }
            } catch (BadSensorUriException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IdNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else if (model.getName().equals(SensorModelHelper.SHARK) && model.getVersion().equals("1.03")) {
            Timer t = new Timer();
            try {
                SharkCollector collector = new SharkCollector(serverUri, username, orgId, password, collectorId,
                        debug);
                if (collector.isValid()) {
                    System.out.format("Started polling %s sensor at %s%n", sensor.getName(),
                            Tstamp.makeTimestamp());
                    t.schedule(collector, 0, definition.getPollingInterval() * 1000);
                } else {
                    System.err.format("Cannot poll %s sensor%n", sensor.getName());
                    return false;
                }
            } catch (IdNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (BadSensorUriException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else if (model.getName().equals(SensorModelHelper.STRESS)) {
            Timer t = new Timer();
            try {
                StressCollector collector = new StressCollector(serverUri, username, orgId, password,
                        collectorId, debug);
                if (collector.isValid()) {
                    System.out.format("Started polling %s sensor at %s%n", sensor.getName(),
                            Tstamp.makeTimestamp());
                    t.schedule(collector, 0, definition.getPollingInterval() * 1000);
                } else {
                    System.err.format("Cannot poll %s sensor%n", sensor.getName());
                    return false;
                }
            } catch (IdNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (BadSensorUriException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else if (model.getName().equals(SensorModelHelper.WEATHER)) {
            Timer t = new Timer();
            try {
                NOAAWeatherCollector collector = new NOAAWeatherCollector(serverUri, username, orgId, password,
                        collectorId, debug);
                if (collector.isValid()) {
                    System.out.format("Started polling %s sensor at %s%n", sensor.getName(),
                            Tstamp.makeTimestamp());
                    t.schedule(collector, 0, definition.getPollingInterval() * 1000);
                } else {
                    System.err.format("Cannot poll %s sensor%n", sensor.getName());
                    return false;
                }
            } catch (IdNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (BadSensorUriException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } catch (IdNotFoundException e) {
        System.err.println(e.getMessage());
        return false;
    }
    return true;
}

From source file:com.hs.mail.container.simple.SimpleSpringContainer.java

private static void startPerformanceMonitor(String interval) {
    int period = Integer.parseInt(interval);
    Timer timer = new Timer();
    TimerTask memoryTask = new TimerTask() {
        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();

        @Override/*w w w .  j a  v  a2  s.  c om*/
        public void run() {
            int threadCount = threadBean.getThreadCount();
            int peakThreadCount = threadBean.getPeakThreadCount();
            MemoryUsage heap = memoryBean.getHeapMemoryUsage();
            MemoryUsage nonHeap = memoryBean.getNonHeapMemoryUsage();
            System.out.println(sdf.format(System.currentTimeMillis()) + "\t threads=" + threadCount
                    + ";peakThreads=" + peakThreadCount + ";heap=" + heap + ";non-heap=" + nonHeap);
        }
    };
    timer.schedule(memoryTask, 0, period * 1000);
}