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

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

  • 相关阅读:
    以太坊:区块(Blocks)
    以太坊:事件日志 (Event Logs)
    以太坊:节点代理(Geth/Parity Proxy) APIs
    以太坊:代币信息 Token
    以太坊:Etherscan API 约定
    以太坊:账号(Account)
    以太坊:智能合约(Contracts)
    我的友情链接
    我的友情链接
    我的友情链接
  • 原文地址:https://www.cnblogs.com/lidelin/p/11771697.html
Copyright © 2020-2023  润新知