Example usage for java.util TimerTask TimerTask

List of usage examples for java.util TimerTask TimerTask

Introduction

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

Prototype

protected TimerTask() 

Source Link

Document

Creates a new timer task.

Usage

From source file:com.shanet.relayremote.Background.java

public Background(Context context, final char op, boolean isWidget) {
    this.context = context;
    this.op = op;
    this.isWidget = isWidget;

    // If a widget, don't show any dialogs
    if (isWidget)
        return;/* ww  w.  ja v  a  2 s  .c  o m*/

    dialog = new ProgressDialog(context);

    // Show a dialog if the bg thread runs longer than the time specified in onPreExecute() below
    timer = new Timer();
    tt = new TimerTask() {
        @Override
        public void run() {
            Looper.prepare();
            ((Activity) Background.this.context).runOnUiThread(new Runnable() {
                public void run() {
                    dialog = ProgressDialog.show(Background.this.context, "", Background.this.context.getString(
                            (op == Constants.OP_SET) ? R.string.connServer : R.string.gettingStates));
                }
            });
        }
    };
}

From source file:fr.calamus.common.db.core.DbAccessFactory.java

private static void launchInstancesObserver() {
    /*Thread run = new Thread() {
       @Override//from  www.j  a  v a2s.c  om
       public void run() {
    while (true) {
       try {
          Thread.currentThread().wait(10000);
          synchronized (instances) {
             long now = System.currentTimeMillis();
             List<String> toRemove = new ArrayList<>();
             for (String id : instances.keySet()) {
                AdeDbFactory db = instances.get(id);
                if (db == null || now > db.lastUsedTime() + db.adeTimeOut()) {
                   toRemove.add(id);
                }
             }
             log.debug("removing " + toRemove.size() + " instance(s)");
             for (String id : toRemove) {
                instances.remove(id);
             }
          }
       } catch (InterruptedException ex) {
          log.warn(ex);
       }
    }
       }
    };
    run.start();*/
    Timer timer = new Timer("DbAccessFactory-instancesRemover", true);
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            synchronized (instances) {
                long now = System.currentTimeMillis();
                List<String> toRemove = new ArrayList<>();
                for (String id : instances.keySet()) {
                    DbAccess db = instances.get(id);
                    if (id != null && (db == null || now > db.lastUsedTime() + timeOut())) {
                        toRemove.add(id);
                    }
                }
                for (String id : toRemove) {
                    instances.remove(id);
                }
                if (toRemove.size() > 0)
                    log.debug("removed " + toRemove.size() + " instance(s); remaining " + instances.size());
            }
        }
    };
    timer.schedule(task, 30000, 10000);
}

From source file:cz.cvut.fel.webrtc.handlers.WebHandler.java

public WebHandler() {
    super();/*from   w  ww .  j a  v a 2 s. com*/
    TimerTask task = new TimerTask() {

        @Override
        public void run() {
            Calendar currentDate = Calendar.getInstance();

            for (WebUser user : registry.getAll()) {
                Calendar ping = user.getLastPing();
                ping.add(Calendar.SECOND, 40);

                if (ping.before(currentDate)) {
                    try {
                        log.info("{} is unreachable.", user.getName());
                        leaveRoom(user);
                    } catch (Exception e) {
                    }
                }
            }
        }

    };

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(task, 30000, 30000);
}

From source file:ch.rasc.s4ws.snake.SnakeTimer.java

public static void startTimer() {
    gameTimer = new Timer(SnakeTimer.class.getSimpleName() + " Timer");
    gameTimer.scheduleAtFixedRate(new TimerTask() {
        @Override//from  www .j  a  v  a2  s.  c om
        public void run() {
            try {
                tick();
            } catch (RuntimeException e) {
                log.error("Caught to prevent timer from shutting down", e);
            }
        }
    }, TICK_DELAY, TICK_DELAY);
}

From source file:com.cnaude.purpleirc.Utilities.UpdateChecker.java

public void asyncUpdateCheck(final CommandSender sender, final String mode) {
    Timer t = new Timer();
    t.schedule(new TimerTask() {
        @Override//  w ww .j  a  v  a2s  .c o m
        public void run() {
            if (plugin.isUpdateCheckerEnabled()) {
                updateCheck(sender, mode);
            }
        }
    }, 0);
}

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

protected void scheduleflushCache() {
    TimerTask flushTask = new TimerTask() {
        @Override//from  www.j  a v  a2 s .  co  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:eindberetning.it_minds.dk.eindberetningmobil_android.fake.FakeFailingServer.java

private void handleCallback(final ResultCallback callback) {
    final Runnable toRun = new Runnable() {
        @Override//w ww  .j a v  a  2 s .c  o m
        public void run() {
            callback.onError(toSendBack);
        }
    };
    innerTime.schedule(new TimerTask() {
        @Override
        public void run() {
            if (mainActivity != null) {
                mainActivity.runOnUiThread(toRun);
            } else if (tester != null) {
                try {
                    tester.runTestOnUiThread(toRun);
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                }
            }
        }
    }, callbackTimeInMs);
}

From source file:com.anritsu.mcrepositorymanager.utils.Packing.java

public Packing(ArrayList<McPackage> packageListToBePacked) {
    this.packageListToBePacked = packageListToBePacked;
    archiveNameFile = new File(REPOSITORY_LOCATION + ARCHIVE_NAME);
    try {/*  ww  w . java  2s  .c  om*/
        out = new ZipOutputStream(new FileOutputStream(archiveNameFile));
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Packing.class.getName()).log(Level.SEVERE, null, ex);
    }

    for (McPackage p : packageListToBePacked) {
        p.setPackageSize(getPackageSize(p));
    }

    // Update status.packageDownloadedSize
    Timer t = new Timer();
    t.schedule(new TimerTask() {
        @Override
        public void run() {

            try {
                String fileName = status.getProcessingPackage().getFileName();
                File f = new File(FOLDER_PATH + fileName);
                status.getProcessingPackage().setPackageDownloadedSize(f.length());
            } catch (Exception exp) {
                status.getProcessingPackage().setPackageDownloadedSize(0);
            }
        }
    }, 0, 1000);
}

From source file:ispok.pokerclock.TournamentController.java

public TournamentController() {

    levelBreak = false;//from w w w .java 2s . com
    paused = false;
    entries = 0;
    prizePool = 0;
    currentLevelDuration_s = 0;
    time_s = currentLevelDuration_s;
    currentLevel = new LevelDto();
    playerDtos = new ArrayList<>(50);
    payoutPlaceDtos = new ArrayList<>(20);
    tournamentDto = null;

    timerCounter = new TimerTask() {
        @Override
        public void run() {
            decTime();
        }
    };
}

From source file:ctlogger.CTlogger.java

public static void main(String args[]) {

    /**/*w w  w  .j  a v  a2  s .  com*/
     * 
     * 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);
    }
}