zoukankan      html  css  js  c++  java
  • java定时案例

         好久没写笔记了,变懒了!

        java定时运行的三个案例:

    一, 通过sleep方法来达到定时任务的效果 

    public class testTime {
        public static void main(String[] args) {
            // 设定时间间隔为1秒
            final long timeInterval = 1000;
            Runnable runnable = new Runnable() {
                public void run() {
                    while (true) {
                        // 执行任务
                        System.out.println("Hello !!");
                        try {
                            Thread.sleep(timeInterval);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            Thread thread = new Thread(runnable);
            thread.start();
        }
    }

    二,TimerTask

    public class testTime2 {
        public static void main(String[] args) {  
            TimerTask task = new TimerTask() {   
                public void run() {   
                    System.out.println("执行!");  
                }  
            };  
            Timer timer = new Timer();  
            long delay = 0;  
            long intevalPeriod = 1 * 1000;   
            timer.scheduleAtFixedRate(task, delay, intevalPeriod);  
        }    
    }

    三,ScheduledExecutorService

    public class testTime3 {
        public static void main(String[] args) {  
            Runnable runnable = new Runnable() {  
                public void run() {   
                    System.out.println("执行!");  
                }  
            };  
            ScheduledExecutorService service = Executors  
                    .newSingleThreadScheduledExecutor();  
            // “10”延时时间,“1”为定时执行的间隔时间,  TimeUnit.SECONDS为时间单位
            service.scheduleAtFixedRate(runnable, 10, 1, TimeUnit.SECONDS);  
        }  
    }

    以上三个案例笔者均已验证!

  • 相关阅读:
    C++ STL——list
    C++ STL——deque
    C++ STL——string和vector
    C++ STL——C++容器的共性和相关概念
    C++ STL——输入输出流
    C++ STL——异常
    C++ STL——类型转换
    C++ STL——模板
    使用PYTHON统计项目代码行数
    在Ubuntu 16.04 LTS下编译安装OpenCV 4.1.1
  • 原文地址:https://www.cnblogs.com/lidelin/p/11771697.html
Copyright © 2011-2022 走看看