zoukankan      html  css  js  c++  java
  • Java 定时循环运行程序

    Timer 和 ScheduledExecutorSeruvce 都能执行定时的循环任务,有函数 scheduleAtFixedRate。但是,如果任务运行时间较长,超过了一个周期时长,下一个任务就会被延缓执行。

    例如代码:

     1 public class ScheduledRunnableTest extends TimerTask {
     2     public void run() {
     3         try {
     4             Thread.sleep(2000);
     5             System.out.println(new Timestamp(System.currentTimeMillis()).toString());
     6         } catch (InterruptedException e) {
     7             e.printStackTrace();
     8         }
     9     }
    10 
    11     public static void main(String[] args) {
    12         Timer timer = new Timer();
    13         timer.scheduleAtFixedRate(new ScheduledRunnableTest(), 0, 1000);
    14     }
    15 }

    运行结果为:

    2014-07-31 13:12:30.002

    2014-07-31 13:12:32.006

    2014-07-31 13:12:34.006

    2014-07-31 13:12:36.008

    并不是希望的每秒运行一次。所以得重开线程执行,代码如下:

     1 public class ScehduledThreadTest extends Thread{
     2     public void run() {
     3         try {
     4             Thread.sleep(2000);
     5             System.out.println(new Timestamp(System.currentTimeMillis()).toString());
     6         } catch (InterruptedException e) {
     7             e.printStackTrace();
     8         }
     9     }
    10 
    11     public static void main(String[] args) {
    12         Timer timer = new Timer();
    13         timer.scheduleAtFixedRate(new TimerTask() {
    14                                             public void run() {
    15                                                 new ScehduledThreadTest().start();
    16                                             }
    17                                         }, 
    18                                     0, 1000);
    19     }
    20 }

    这样的结果就是:

    2014-07-31 13:15:10.652

    2014-07-31 13:15:11.652

    2014-07-31 13:15:12.652

     

     

     

  • 相关阅读:
    nginx预防常见攻击
    nginx性能优化(针对于高并发量仅供参考,并不是方案)
    nginx平滑升级(1.14--1.15)
    LAMP动静分离安装(源码安装)
    洛谷-P1098 字符串的展开
    洛谷-P1086 花生采摘
    洛谷-P1042 乒乓球
    洛谷-P1031 均分纸牌
    洛谷-P1023 税收与补贴问题
    洛谷-P1125 笨小猴
  • 原文地址:https://www.cnblogs.com/keepthinking/p/3880589.html
Copyright © 2011-2022 走看看