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:ctlogger.CTlogger.java

public static void main(String args[]) {

    /**/*from ww w.j a  va  2 s .  c  o m*/
     * 
     * Original code for command line parsing
     * (This has been replaced by code using Apache Commons CLI, see below)
     *
    String helpMsg = "CTlogger -x -r -z -g -k <skiplines> -f <flush_sec> -p <poll_sec> -n <nanVal> -i <leadingID> -s <SourceName> -H <HeaderLine> <logger.dat> <CTfolder>";
      int dirArg = 0;
      while((dirArg<args.length) && args[dirArg].startsWith("-")) {      // arg parsing
         if(args[dirArg].equals("-h"))    { 
     System.err.println(helpMsg);
     System.exit(0);
         }
         if(args[dirArg].equals("-x"))    { debug = true;   }
         if(args[dirArg].equals("-b"))    { noBackwards = true;   }
         if(args[dirArg].equals("-g"))    { gzipmode = true;   }         // default false
         if(args[dirArg].equals("-a"))    { appendMode = false;   }      // default true
         if(args[dirArg].equals("-z"))     { zipmode = false; }          // default true
         if(args[dirArg].equals("-N"))    { newFileMode = true;   }      // default false
         if(args[dirArg].equals("-f"))   { autoflush = Long.parseLong(args[++dirArg]); }
         if(args[dirArg].equals("-p"))   { pollInterval = Long.parseLong(args[++dirArg]); }
         if(args[dirArg].equals("-k"))   { skipLines = Long.parseLong(args[++dirArg]); }
         if(args[dirArg].equals("-r"))   { repeatFetch = true; }   
         if(args[dirArg].equals("-B"))   { blockMode = true; }   
         if(args[dirArg].equals("-t"))   { storeTime = true; }   
         if(args[dirArg].equals("-T"))   { trimTime = Double.parseDouble(args[++dirArg]); }
         if(args[dirArg].equals("-n"))   { nanVal = args[++dirArg]; }
         if(args[dirArg].equals("-i"))   { leadingID = args[++dirArg]; }
         if(args[dirArg].equals("-s"))   { SourceName = args[++dirArg]; }
         if(args[dirArg].equals("-H"))   { HeaderLine = args[++dirArg]; }
         dirArg++;
      }
    if(args.length < (dirArg+2)) {
       System.err.println(helpMsg);
       System.exit(0);
    }
    loggerFileName = args[dirArg++];      // args[0]:  logger.dat file
    CTrootfolder = args[dirArg++];         // args[1]:  CT destination folder        
    */

    //
    // Parse command line arguments
    //
    // 1. Setup command line options
    //
    Options options = new Options();
    // Boolean options (only the flag, no argument)
    options.addOption("h", "help", false, "Print this message");
    options.addOption("x", "debug", false, "turn on debug output");
    options.addOption("b", "nobackwards", false, "no backwards-going time allowed");
    options.addOption("g", "gzipmode", false, "turn on gzip for extra compression");
    options.addOption("a", "noappend", false,
            "turn off append mode (i.e., do not append to end of existing CT data)");
    options.addOption("z", "nozip", false, "turn off zip mode (it is on by default)");
    options.addOption("N", "newfilemode", false, "re-parse entire logger file every time it is checked");
    options.addOption("r", "repeatFetch", false, "turn on repeat fetch (auto-fetch data loop)");
    options.addOption("B", "blockMode", false,
            "turn on CloudTurbine writer block mode (multiple points per output data file, packed data)");
    options.addOption("t", "storeTime", false,
            "store time string as a channel; time is the first data entry in each line; if this option is not specified, then the time channel is skipped/not saved to CloudTurbine");
    // Options with an argument
    Option outputFolderOption = Option.builder("f").argName("autoflush").hasArg()
            .desc("flush interval (sec); default = \"" + autoflush + "\"").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("p").argName("pollInterval").hasArg().desc(
            "if repeatFetch option has been specified, recheck the logger data file at this polling interval (sec); default = \""
                    + pollInterval + "\"")
            .build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("k").argName("skipLines").hasArg().desc(
            "in logger file, the num lines to skip after the header line to get to the first line of data; default = \""
                    + skipLines + "\"")
            .build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("T").argName("trimTime").hasArg().desc(
            "trim (ring-buffer loop) time (sec) (trimTime=0 for indefinite); default = \"" + trimTime + "\"")
            .build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("n").argName("nanVal").hasArg()
            .desc("replace NAN with this; default = \"" + nanVal + "\"").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("i").argName("leadingID").hasArg()
            .desc("leading ID string (IWG1 compliant)").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("s").argName("sourceName").hasArg()
            .desc("CloudTurbine source name; default = \"" + SourceName + "\"").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("H").argName("HeaderLine").hasArg().desc(
            "optional CSV list of channel names; if not supplied, this is read from the first line in the logger file")
            .build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("l").argName("loggerfilename").hasArg()
            .desc("name of the logger data file; required argument").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("o").longOpt("outputfolder").argName("folder").hasArg()
            .desc("Location of output files (source is created under this folder); default = " + CTrootfolder)
            .build();
    options.addOption(outputFolderOption);

    //
    // 2. Parse command line options
    //
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException exp) {
        // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }

    //
    // 3. Retrieve the command line values
    //
    if (line.hasOption("help")) {
        // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("CTlogger", options);
        return;
    }
    debug = line.hasOption("x");
    noBackwards = line.hasOption("b");
    gzipmode = line.hasOption("g");
    appendMode = !line.hasOption("a");
    zipmode = !line.hasOption("z");
    newFileMode = line.hasOption("N");
    repeatFetch = line.hasOption("r");
    blockMode = line.hasOption("B");
    storeTime = line.hasOption("t");
    autoflush = Long.parseLong(line.getOptionValue("f", Long.toString(autoflush)));
    pollInterval = Long.parseLong(line.getOptionValue("p", Long.toString(pollInterval)));
    skipLines = Long.parseLong(line.getOptionValue("k", Long.toString(skipLines)));
    trimTime = Double.parseDouble(line.getOptionValue("T", Double.toString(trimTime)));
    nanVal = line.getOptionValue("n", nanVal);
    if (line.hasOption("i")) {
        leadingID = line.getOptionValue("i");
    }
    SourceName = line.getOptionValue("s", SourceName);
    if (line.hasOption("H")) {
        HeaderLine = line.getOptionValue("H");
    }
    if (line.hasOption("l")) {
        loggerFileName = line.getOptionValue("l");
    } else {
        System.err.println("ERROR: you must supply the logger file name.");
        return;
    }
    CTrootfolder = line.getOptionValue("o", CTrootfolder);

    if (!debug) {
        System.err.println("CTlogger: " + loggerFileName + ", CTrootfolder: " + CTrootfolder
                + ", pollInterval: " + pollInterval);
    } else {
        System.err.println("debug = " + debug);
        System.err.println("noBackwards = " + noBackwards);
        System.err.println("gzipmode = " + gzipmode);
        System.err.println("appendMode = " + appendMode);
        System.err.println("zipmode = " + zipmode);
        System.err.println("newFileMode = " + newFileMode);
        System.err.println("repeatFetch = " + repeatFetch);
        System.err.println("blockMode = " + blockMode);
        System.err.println("storeTime = " + storeTime);
        System.err.println("autoflush = " + autoflush);
        System.err.println("pollInterval = " + pollInterval);
        System.err.println("skipLines = " + skipLines);
        System.err.println("trimTime = " + trimTime);
        System.err.println("nanVal = " + nanVal);
        System.err.println("leadingID = " + leadingID);
        System.err.println("SourceName = " + SourceName);
        System.err.println("HeaderLine = " + HeaderLine);
        System.err.println("loggerFileName = " + loggerFileName);
        System.err.println("CTrootfolder = " + CTrootfolder);
    }

    //
    // Run CTlogger
    //
    if (!repeatFetch)
        getData(true); // run once
    else {
        Timer timer = new Timer();
        TimerTask fetchTask = new TimerTask() {
            @Override
            public void run() {
                if (newFileMode)
                    getData(true);
                else if (getData(false)) { // pick up from old data if you can
                    System.err.println("Failed to pick up from old data, refetch from start of file...");
                    boolean status = getData(true);
                    System.err.println("refetch status: " + status);
                }
                if (debug)
                    System.err.println("Waiting for data, pollInterval: " + pollInterval + " sec...");
            };
        };
        // repeatFetch@autoflush interval, convert to msec
        if ((autoflush > 0) && (pollInterval > autoflush))
            pollInterval = autoflush;
        timer.scheduleAtFixedRate(fetchTask, 0, pollInterval * 1000);
    }
}

From source file:ru.asmsoft.p2p.storage.MemoryNodesRepository.java

@PostConstruct
public void init() {

    Cache<String, Node> cache = CacheBuilder.newBuilder()
            .expireAfterAccess(config.getHeartbeatPeriodExpired(), TimeUnit.MILLISECONDS).removalListener(this)
            .build();/*from  ww  w .j  a v  a  2s. c  om*/
    nodes = cache.asMap();

    // Initialization delay (Heartbeat period * 2)
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            logger.debug("NodesRepository is ready.");
            isInitialised = true;
        }
    }, config.getHeartbeatPeriod() * 2);

}

From source file:com.tencent.mars.proxy.NetMsgHeaderHandler.java

public NetMsgHeaderHandler() {
    super();//from w  w w . java 2 s.  c o  m

    checker = new ContextTimeoutChecker();
    Timer timer = new Timer();
    timer.schedule(checker, 15 * 60 * 1000, 15 * 60 * 1000);
}

From source file:edu.mayo.cts2.framework.plugin.service.lexevs.security.msso.RestMssoUserValidator.java

protected void scheduleflushCache() {
    TimerTask flushTask = new TimerTask() {
        @Override//from  ww  w. ja  v a  2s  . c  o  m
        public void run() {
            synchronized (mutex) {
                tokenCache.clear();
            }
        }
    };

    Timer timer = new Timer();

    int minutesInMillis = FLUSH_PERIOD_MINUTES * 60 * 1000;
    timer.schedule(flushTask, 0, minutesInMillis);
}

From source file:org.eclipse.swordfish.core.util.SimpleClient.java

public void start() {
    checkConstraints();/*from  w w  w .  j av  a2  s.c  o m*/
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            try {
                sendRequestSynchronously();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }, delayBeforeSending);

}

From source file:gov.nih.nci.caxchange.messaging.RegistrationLoadTest.java

/**
 * Testcase for sending the messages/*from   w w  w .  jav a 2s.  c o m*/
 * 
 * @throws InterruptedException - InterruptedException
 */
@Test
public void sendRegistrationMessage() throws InterruptedException {

    final Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(currDt.getTime() + 5000);
    currDt = calendar.getTime();

    final Timer timer = new Timer();
    timer.schedule(getTimerTask(0), currDt);
    timer.schedule(getTimerTask(1), currDt);
    timer.schedule(getTimerTask(2), currDt);
    timer.schedule(getTimerTask(3), currDt);
    timer.schedule(getTimerTask(4), currDt);
    timer.schedule(getTimerTask(5), currDt);
    timer.schedule(getTimerTask(6), currDt);
    timer.schedule(getTimerTask(7), currDt);
    timer.schedule(getTimerTask(8), currDt);
    timer.schedule(getTimerTask(9), currDt);
    timer.schedule(getTimerTask(10), currDt);
    timer.schedule(getTimerTask(11), currDt);
    timer.schedule(getTimerTask(12), currDt);
    timer.schedule(getTimerTask(13), currDt);
    timer.schedule(getTimerTask(14), currDt);
    timer.schedule(getTimerTask(15), currDt);
    timer.schedule(getTimerTask(16), currDt);
    timer.schedule(getTimerTask(17), currDt);
    timer.schedule(getTimerTask(18), currDt);
    timer.schedule(getTimerTask(19), currDt);

    es.awaitTermination(3, TimeUnit.MINUTES);
}

From source file:io.s4.core.WindowingPE.java

/**
 * Constructor for time-based slots. The abstract method
 * {@link #addPeriodicSlot()} is called periodically.
 * // www  .ja v  a 2 s. co m
 * @param app
 *            the application
 * @param slotDuration
 *            the slot duration in timeUnit
 * @param timeUnit
 *            the unit of time
 * @param numSlots
 *            the number of slots to be stored
 */
public WindowingPE(App app, long slotDuration, TimeUnit timeUnit, int numSlots) {
    super(app);
    this.numSlots = numSlots;

    if (slotDuration > 0l) {
        slotDurationInMilliseconds = TimeUnit.MILLISECONDS.convert(slotDuration, timeUnit);
        timer = new Timer();
        timer.schedule(new SlotTask(), slotDurationInMilliseconds, slotDurationInMilliseconds);
        logger.trace("TIMER: " + slotDurationInMilliseconds);

    } else {
        slotDurationInMilliseconds = 0;
        timer = null;
    }
}

From source file:net.pms.util.TempFileMgr.java

public void schedule() {
    TimerTask task = new TimerTask() {
        @Override//w ww . j  a v a  2 s .co m
        public void run() {
            scan();
        }
    };
    Timer t = new Timer();
    t.scheduleAtFixedRate(task, 0, INTERVAL);
}

From source file:edu.iu.dymoro.Scheduler.java

public Scheduler(int numRowSplits, int numColSplits, Int2ObjectOpenHashMap<D>[] vWHMap, long time,
        List<T> tasks) {//from   w  ww . j ava 2s  .c o m
    rowCount = new int[numRowSplits];
    this.numRowSplits = numRowSplits;
    numRowLimit = numColSplits;
    freeRow = new int[numRowSplits];
    numFreeRows = 0;
    colCount = new int[numColSplits];
    this.numColSplits = numColSplits;
    numColLimit = numRowSplits;
    freeCol = new int[numColSplits];
    numFreeCols = 0;
    splitMap = new byte[numRowSplits][numColSplits];
    numItemsTrained = 0L;
    this.vWHMap = vWHMap;

    this.time = time;
    this.timer = new Timer();
    random = new Random(System.currentTimeMillis());
    isRunning = new AtomicBoolean(true);
    compute = new DynamicScheduler<>(tasks);
    compute.start();
}

From source file:mina.UnsyncClientSupport.java

/**
 * FTS?/* w w w.java  2s .c o m*/
 * 
 * @return
 * @throws CommunicationException
 * @throws InterruptedException
 */
public IoSession connect() throws InterruptedException {
    timer = new Timer();
    if (null != this.session && !session.isConnected()) {
        //??
        return this.session;
    }
    if (connector != null) {
        connector.connect();
        return this.session;
    }
    connector = new NioSocketConnector();
    connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
    connector.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newSingleThreadExecutor()));
    connector.getFilterChain().addLast("logger", new LoggingFilter());
    connector.setHandler(new ClientMsgReceiveHandle());// ???
    try {
        connector.setDefaultRemoteAddress(
                new InetSocketAddress(EPSConstant.UNSYNC_CLIENT_IP, EPSConstant.UNSYNC_CLIENT_PORT));
        ConnectFuture future = connector.connect(new InetSocketAddress(this.hostname, this.port));
        future.awaitUninterruptibly();
        IoSession session = future.getSession();
        this.setSession(session);
        //???????
        timer = new Timer();
        timer.schedule(new HoldConnectionTask(), 0, 60000);
    } catch (RuntimeIoException e) {
        e.printStackTrace();
    }
    return session;
}