java.util.TimerTask Java Examples

The following examples show how to use java.util.TimerTask. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Metrics.java    From NeuralNetworkAPI with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Starts the Scheduler which submits our data every 30 minutes.
 */
private void startSubmitting() {
    final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if (!plugin.isEnabled()) { // Plugin was disabled
                timer.cancel();
                return;
            }
            // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
            // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
            Bukkit.getScheduler().runTask(plugin, new Runnable() {
                @Override
                public void run() {
                    submitData();
                }
            });
        }
    }, 1000*60*5, 1000*60*30);
    // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
    // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
    // WARNING: Just don't do it!
}
 
Example #2
Source File: ContainerMetrics.java    From big-c with Apache License 2.0 6 votes vote down vote up
private synchronized void scheduleTimerTaskIfRequired() {
  if (flushPeriodMs > 0) {
    // Lazily initialize timer
    if (timer == null) {
      this.timer = new Timer("Metrics flush checker", true);
    }
    TimerTask timerTask = new TimerTask() {
      @Override
      public void run() {
        synchronized (ContainerMetrics.this) {
          if (!finished) {
            flushOnPeriod = true;
          }
        }
      }
    };
    timer.schedule(timerTask, flushPeriodMs);
  }
}
 
Example #3
Source File: ThreadWarningSystem.java    From gate-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Monitor only deadlocks.
 */
public ThreadWarningSystem() {
  threadCheck.schedule(new TimerTask() {
    @Override
    public void run() {
      long[] ids = mbean.findMonitorDeadlockedThreads();
      if (ids != null && ids.length > 0) {
        for (Long l : ids) {
          if (!deadlockedThreads.contains(l)) {
            deadlockedThreads.add(l);
            ThreadInfo ti = mbean.getThreadInfo(l, MAX_STACK_DEPTH);
            fireDeadlockDetected(ti);
          }
        }
      }
    }
  }, 10, DEADLOCK_CHECK_PERIOD);
}
 
Example #4
Source File: ViewErrorsActivity.java    From bitseal with GNU General Public License v3.0 6 votes vote down vote up
protected void onResume() 
{
	super.onResume();
	
	// Check for new log lines regularly and update the ListView if any are found
       refreshListTask = new TimerTask()
    {
        @Override
        public void run() 
        {
            runOnUiThread(new Runnable()
            {
                public void run() 
                {
                	if (checkForNewLines())
                	{
                		updateListView();
                	}
                }
            });
        }
    };
    new Timer().schedule(refreshListTask, 0, UPDATE_FREQUENCY_MILLISECONDS);
}
 
Example #5
Source File: FedSumUpdate.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Update Index after a fixed interval
 * @param lstEndPoints List of SPARQL endpoints
 * @param interval Interval in milliseconds
 * @param outputFile Output location of index
 */
public static void updateIndexAtFixedRate(final List<String> lstEndPoints, long interval, final String outputFile) {
	Timer timer = new Timer();
	timer.scheduleAtFixedRate(new TimerTask() {public void run() { 	 try {
		FedSumGenerator generator = new FedSumGenerator(outputFile);
		long startTime = System.currentTimeMillis();
		generator.generateSummaries(lstEndPoints);
		System.out.println("Index is secessfully updated to "+ outputFile);
		System.out.println("Data Summaries Generation Time (sec): "+ (System.currentTimeMillis()-startTime)/1000);

	} catch (IOException | RepositoryException | MalformedQueryException | QueryEvaluationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	}  }, 0, interval);

	}
 
Example #6
Source File: MusicService.java    From SMP with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onSeekComplete(MediaPlayer mp) {
    // on a 4.1 phone no bug : calling getCurrentPosition now gives the new seeked position
    // on My 2.3.6 phone, the phone seems bugged : calling now getCurrentPosition gives
    // last position. So wait the seekpos goes after the asked seekpos.
    if(seekPosBug != -1) {
        // todo: make it thread safe?
        seekPosNbLoop = seekPosMaxLoop;

        final Timer seekPosTimer = new Timer();
        seekPosTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (seekPosNbLoop-- > 0 || getCurrentPosition() >= seekPosBug) {
                    seekFinished = true;
                    seekPosBug = -1;
                    seekPosTimer.cancel();
                }
            }
        }, 300);
    }
    else {
        seekFinished = true;
    }
    Log.d("MusicService", "onSeekComplete setProgress" + RowSong.secondsToMinutes(getCurrentPosition()));
}
 
Example #7
Source File: PeerConnectionClient.java    From voip_android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void enableStatsEvents(boolean enable, int periodMs) {
    if (enable) {
        try {
            statsTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            getStats();
                        }
                    });
                }
            }, 0, periodMs);
        } catch (Exception e) {
            Log.e(TAG, "Can not schedule statistics timer", e);
        }
    } else {
        statsTimer.cancel();
    }
}
 
Example #8
Source File: Metrics.java    From SubServers-2 with Apache License 2.0 6 votes vote down vote up
private void startSubmitting() {
    // We use a timer cause want to be independent from the server tps
    final Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            // Plugin was disabled, e.g. because of a reload (is this even possible in Sponge?)
            if (!Sponge.getPluginManager().isLoaded(plugin.plugin.getId())) {
                timer.cancel();
                return;
            }
            // The data collection (e.g. for custom graphs) is done sync
            // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
            Scheduler scheduler = Sponge.getScheduler();
            Task.Builder taskBuilder = scheduler.createTaskBuilder();
            taskBuilder.execute(() -> submitData()).submit(plugin);
        }
    }, 1000*60*5, 1000*60*30);
    // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
    // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
    // WARNING: Just don't do it!
}
 
Example #9
Source File: TimerTest.java    From werewolf_server with Apache License 2.0 6 votes vote down vote up
@Test
    public  void timeTest(){
        Timer timer = new Timer();
        CountDownLatch countDownLatch = new CountDownLatch(1);
        timer.schedule(new TimerTask(){

            @Override
            public void run() {
                System.out.println("hahh");
                countDownLatch.countDown();
            }
        },  10000);
        try {
//            timer.cancel();  //取消定时器
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
Example #10
Source File: DelayOverflow.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {
    for (int how=0; how<4; how++) {
        final CountDownLatch done = new CountDownLatch(1);
        final AtomicInteger count = new AtomicInteger(0);
        final Timer timer = new Timer();
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                checkScheduledExecutionTime(this);
                count.incrementAndGet();
                done.countDown();
            }};

        scheduleNow(timer, task, how);
        done.await();
        equal(count.get(), 1);
        checkScheduledExecutionTime(task);
        if (new java.util.Random().nextBoolean())
            sleep(10);
        check(task.cancel());
        timer.cancel();
        checkScheduledExecutionTime(task);
    }
}
 
Example #11
Source File: JupyterStreamWriter.java    From jupyter-kernel-jsr223 with Apache License 2.0 6 votes vote down vote up
private void streaming() {
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            StringBuffer sb = getBuffer();
            synchronized (sb) {
                if (sb.length() > 0) {
                    String S = sb.toString();
                    flush();
                    sb.delete(0, sb.length());
                    ((T_stream) message.msg.content).text = S;
                    message.send();
                }
            }
        }
    }, 250, 250);
}
 
Example #12
Source File: SourceHandler.java    From metron with Apache License 2.0 6 votes vote down vote up
private void initialize() throws IOException {
  LOG.debug("Initializing Source Handler");
  this.fs = FileSystem.get(new Configuration());
  this.currentFile = createOutputFile();
  LOG.debug("Source Handler initialized with starting file: {}", currentFile);
  if(this.rotationPolicy instanceof TimedRotationPolicy){
    long interval = ((TimedRotationPolicy)this.rotationPolicy).getInterval();
    this.rotationTimer = new Timer(true);
    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        try {
          LOG.debug("Rotating output file from TimerTask");
          rotateOutputFile();
        } catch(IOException e){
          LOG.warn("IOException during scheduled file rotation.", e);
        }
      }
    };
    this.rotationTimer.scheduleAtFixedRate(task, interval, interval);
  }
}
 
Example #13
Source File: AbstractNSQClient.java    From TrendrrNSQClient with MIT License 6 votes vote down vote up
/**
 * connects, ready to produce.
 */
public synchronized void start() {
    this.connect();

    if (timer != null) {
        timer.cancel();
    }
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            try {
                connect();
            } catch (Throwable t) {
                log.error("Error in periodic `connect` call", t);
            }
        }
    }, lookupPeriod, lookupPeriod);
}
 
Example #14
Source File: PeerConnectionClient.java    From sample-videoRTC with Apache License 2.0 6 votes vote down vote up
public void enableStatsEvents(boolean enable, int periodMs) {
  if (enable) {
    try {
      statsTimer.schedule(new TimerTask() {
        @Override
        public void run() {
          executor.execute(new Runnable() {
            @Override
            public void run() {
              getStats();
            }
          });
        }
      }, 0, periodMs);
    } catch (Exception e) {
      Log.e(TAG, "Can not schedule statistics timer", e);
    }
  } else {
    statsTimer.cancel();
  }
}
 
Example #15
Source File: RedeliveryQueueImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected final synchronized void schedule() {
    if (null == manager.getTimer()) {
        return;
    }
    class RedeliverTask extends TimerTask {
        RedeliverCandidate candidate;

        RedeliverTask(RedeliverCandidate c) {
            candidate = c;
        }

        @Override
        public void run() {
            if (!candidate.isPending()) {
                candidate.initiate();
            }
        }
    }
    nextTask = new RedeliverTask(this);
    try {
        manager.getTimer().schedule(nextTask, next);
    } catch (IllegalStateException ex) {
        LOG.log(Level.WARNING, "SCHEDULE_RESEND_FAILED_MSG", ex);
    }
}
 
Example #16
Source File: DelayOverflow.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
void scheduleNow(Timer timer, TimerTask task, int how) {
    switch (how) {
        case 0 :
            timer.schedule(task, new Date(), Long.MAX_VALUE);
            break;
        case 1:
            timer.schedule(task, 0L, Long.MAX_VALUE);
            break;
        case 2:
            timer.scheduleAtFixedRate(task, new Date(), Long.MAX_VALUE);
            break;
        case 3:
            timer.scheduleAtFixedRate(task, 0L, Long.MAX_VALUE);
            break;
        default:
            fail(String.valueOf(how));
    }
}
 
Example #17
Source File: TimerTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testTaskNotCancelledWhenTimerCancelled() throws Exception {
    final int timeSleeping = 200;
    Timer t = new Timer();
    final AtomicLong counter = new AtomicLong();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            try {
                counter.incrementAndGet();
                Thread.sleep(timeSleeping);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
        }
    };
    t.scheduleAtFixedRate(task, 1 /* delay */, 100 /* rate */);
    Thread.sleep(1000);
    t.cancel();
    // Returns true as the task wasn't cancelled before.
    assertTrue(task.cancel());
}
 
Example #18
Source File: AbstractContentReader.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public TimeSizeRestrictedInputStream(InputStream is,
        long timeoutMs, Action timeoutAction,
        long readLimitBytes, Action readLimitAction,
        TransformerDebug transformerDebug)
{
    this.is = useBufferedInputStream ? new BufferedInputStream(is) : is;
    this.timeoutMs = timeoutMs;
    this.timeoutAction = timeoutAction;
    this.readLimitBytes = readLimitBytes;
    this.readLimitAction = readLimitAction;
    this.transformerDebug = transformerDebug;
    
    if (timeoutMs > 0)
    {
        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                timeoutFlag.set(true);
            }
        
        }, timeoutMs);
    }
}
 
Example #19
Source File: ManagerTime.java    From helloiot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void connect() {
    
    disconnect();
    
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        private long lastepochsecond = clock.instant().getEpochSecond();
        @Override
        public void run() {
            long epochsecond = clock.instant().getEpochSecond();
            while (epochsecond - lastepochsecond > 0L) {
                lastepochsecond += 1L;
                byte[] payload = Long.toString(lastepochsecond).getBytes(StandardCharsets.UTF_8);
                consumer.accept(new EventMessage("current", payload));
            }
        }
    }, 0L, 100L);
    
}
 
Example #20
Source File: SplashActivity.java    From SmartOrnament with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    // 设置全屏
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_splash);
    //设置定时器,欢迎界面呈现2秒后跳转进入主界面
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    },2000);
}
 
Example #21
Source File: FileChooserPageBase.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
private void reschedule() {
  if (myUrl == null || myUrl.getHost() == null || myUrl.getHost().length() == 0) {
    onFetchComplete(null);
    return;
  }
  myFetchedFile = null;
  onFetchComplete(null);
  isFetching = true;
  myTimer.schedule(new TimerTask() {
    final URL myUrlAtStart = myUrl;

    @Override
    public void run() {
      synchronized (myTimer) {
        if (!myUrlAtStart.equals(myUrl)) {
          reschedule();
        } else {
          fetch();
        }
      }
    }
  }, 3000);
}
 
Example #22
Source File: CrashXCheckJni.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String []s)
{
    final Dialog fd = new Dialog(new Frame(), true);
    Timer t = new Timer();
    t.schedule(new TimerTask() {

        public void run() {
            System.out.println("RUNNING TASK");
            fd.setVisible(false);
            fd.dispose();
            System.out.println("FINISHING TASK");
        }
    }, 3000L);

    fd.setVisible(true);
    t.cancel();
    Util.waitForIdle(null);

    AbstractTest.pass();
}
 
Example #23
Source File: Metrics.java    From Skript with GNU General Public License v3.0 6 votes vote down vote up
/**
  * Starts the Scheduler which submits our data every 30 minutes.
  */
 private void startSubmitting() {
     final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
     timer.scheduleAtFixedRate(new TimerTask() {
         @SuppressWarnings("synthetic-access")
@Override
         public void run() {
             if (!plugin.isEnabled()) { // Plugin was disabled
                 timer.cancel();
                 return;
             }
             // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
             // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
             Bukkit.getScheduler().runTask(plugin, new Runnable() {
                 @Override
                 public void run() {
                     submitData();
                 }
             });
         }
     }, 1000*60*5, 1000*60*30);
     // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
     // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
     // WARNING: Just don't do it!
 }
 
Example #24
Source File: JCVideoPlayer.java    From JieCaoVideoPlayer-develop with MIT License 6 votes vote down vote up
protected void startProgressTimer() {
    cancelProgressTimer();
    UPDATE_PROGRESS_TIMER = new Timer();
    UPDATE_PROGRESS_TIMER.schedule(new TimerTask() {
        @Override
        public void run() {
            if (getContext() != null && getContext() instanceof Activity) {
                ((Activity) getContext()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mCurrentState == CURRENT_STATE_PLAYING || mCurrentState == CURRENT_STATE_PAUSE) {
                            setTextAndProgress(0);
                        }
                    }
                });
            }
        }
    }, 0, 300);
}
 
Example #25
Source File: Chain.java    From WeCross with Apache License 2.0 6 votes vote down vote up
public void start() {
    if (!running.get()) {
        running.set(true);

        blockSyncThread =
                new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                mainLoop();
                            }
                        });
        blockSyncThread.start();
        logger.trace("Block header sync thread started");

        mainLoopTimer.schedule(
                new TimerTask() {
                    @Override
                    public void run() {
                        noteMainLoop();
                    }
                },
                mainLoopInterval,
                mainLoopInterval);
    }
}
 
Example #26
Source File: IndexAdmin.java    From search-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@PostConstruct
private void init() {
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            try {// 异步定时更新索引结构
                for (Map.Entry<String, IndexHelper> entry : CACHE.entrySet()) {
                    String[] keyVal = entry.getKey().split(":");
                    String index = keyVal[0];
                    String type = keyVal[1];
                    String mapping = loadIndexStruct(index, type);
                    register(index, type, mapping);
                }
            } catch (Exception e) {
                LOGGER.error("refresh.index.ERROR:" + e.getMessage());
            }
        }
    }, 10000, 5000);
}
 
Example #27
Source File: DelayOverflow.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {
    for (int how=0; how<4; how++) {
        final CountDownLatch done = new CountDownLatch(1);
        final AtomicInteger count = new AtomicInteger(0);
        final Timer timer = new Timer();
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                checkScheduledExecutionTime(this);
                count.incrementAndGet();
                done.countDown();
            }};

        scheduleNow(timer, task, how);
        done.await();
        equal(count.get(), 1);
        checkScheduledExecutionTime(task);
        if (new java.util.Random().nextBoolean())
            sleep(10);
        check(task.cancel());
        timer.cancel();
        checkScheduledExecutionTime(task);
    }
}
 
Example #28
Source File: AbstractWebSocket.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * Start the connection lost timer
 */
protected void startConnectionLostTimer() {
    if (this.connectionLostTimeout <= 0) {
        if (WebSocketImpl.DEBUG)
            System.out.println("Connection lost timer deactivated");
        return;
    }
    if (WebSocketImpl.DEBUG)
        System.out.println("Connection lost timer started");
    cancelConnectionLostTimer();
    connectionLostTimer = new Timer();
    connectionLostTimerTask = new TimerTask() {
        @Override
        public void run() {
            Collection<WebSocket> con = connections();
            synchronized ( con ) {
                long current = (System.currentTimeMillis()-(connectionLostTimeout * 1500));
                for( WebSocket conn : con ) {
                    if (conn instanceof WebSocketImpl) {
                        if( ((WebSocketImpl)conn).getLastPong() < current ) {
                            if (WebSocketImpl.DEBUG)
                                System.out.println("Closing connection due to no pong received: " + conn.toString());
                            conn.close( CloseFrame.ABNORMAL_CLOSE );
                        } else {
                            conn.sendPing();
                        }
                    }
                }
            }
        }
    };
    connectionLostTimer.scheduleAtFixedRate( connectionLostTimerTask,connectionLostTimeout * 1000, connectionLostTimeout * 1000 );
}
 
Example #29
Source File: Loading.java    From ApkToolPlus with Apache License 2.0 5 votes vote down vote up
/**
 * 启动超时计时器
 *
 * @param delay   超时时间,毫秒值
 */
public void lauchTimeoutTimer(long delay){
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            Platform.runLater(() -> showCancelButton());
            timer.cancel();
        }
    },delay);
}
 
Example #30
Source File: ImportDataFromJson.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
protected void importGeometry(ODatabaseDocumentTx db, String file, final String clazz, String geomClazz) throws IOException {

    OClass points = db.getMetadata().getSchema().createClass(clazz);
    points.createProperty("geometry", OType.EMBEDDED, db.getMetadata().getSchema().getClass(geomClazz));
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    OIOUtils.copyStream(new FileInputStream(new File(file)), out, -1);
    ODocument doc = new ODocument().fromJSON(out.toString(), "noMap");
    List<ODocument> collection = doc.field("collection");

//    OShapeFactory builder = OShapeFactory.INSTANCE;

    final AtomicLong atomicLong = new AtomicLong(0);

    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        OLogManager.instance().info(this, clazz + " per second [%d]", atomicLong.get());
        atomicLong.set(0);
      }
    };
    Orient.instance().scheduleTask(task, 1000, 1000);
    for (ODocument entries : collection) {
      ODocumentInternal.removeOwner(entries, doc);
      ODocumentInternal.removeOwner(entries, (ORecordElement) collection);
      entries.setClassName(clazz);
      String wkt = entries.field("GeometryWkt");
      try {
//        ODocument location = builder.toDoc(wkt);
//        entries.field("geometry", location, OType.EMBEDDED);
//        db.save(entries);
//
//        atomicLong.incrementAndGet();
      } catch (Exception e) {

      }
    }
    task.cancel();
  }