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);  
        }  
    }

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

  • 相关阅读:
    学习笔记-php图像等比例剪裁-2016.4.7
    学习日记-2016.3.31
    学习日记--2016.3.30
    I/O扩展篇(基于74HC164/74HC165)
    Visual SVN Server启动失败0x8007042a错误
    CC3000 主机驱动API介绍
    CC3000 SPI接口编程介绍
    struct和typedef struct彻底明白了
    MSP430学习笔记:UART
    DWORD类型的IP地址转换为CString字符串
  • 原文地址:https://www.cnblogs.com/lidelin/p/11771697.html
Copyright © 2011-2022 走看看