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

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

  • 相关阅读:
    phpstorm常用快捷键
    tp3.2.3运用phpexcel将excel文件导入mysql数据库
    TP3.2加载外部PHPexcel类,实现导入和导出
    Navicat常用快捷键
    thnkphp框架面试问题
    PHPSQL注入
    PHP4个载入语句的区别
    goflyway简单使用
    ubuntu16.04 HyperLedger Fabric 1.2.0 开发环境搭建
    DApp demo之pet-shop
  • 原文地址:https://www.cnblogs.com/lidelin/p/11771697.html
Copyright © 2011-2022 走看看