zoukankan      html  css  js  c++  java
  • 七、Timer

    java.util.Timer一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。

    public class TimerTest{
             public static void main(String []args ){
            //创建Timer(定时器)类
            Timer timer = new Timer();
            //创建TimerTask,就是定时器需要执行的代码,任务只能被调度一次,已经调度过的任务不能再调度。
            TimerTask task = new TimerTask() {    //因为任务只能被调度一次,所以一般直接写内部类
                public void run() {
                    System.out.println("xixi");
                }
            };
            /**
             * schedule调度
             *   - void schedule(TimerTask task, Date time)   
             *       在指定的时间执行指定的任务
             *   - void schedule(TimerTask task, Date firstTime, long period)   
             *       在指定的时间执行指定的任务,然后每隔period时间执行一次
             *   - void schedule(TimerTask task, long delay)  
             *       在delay毫秒后执行指定的任务。
             *   - void schedule(TimerTask task, long delay, long period)  
             *       在delay毫秒后执行指定的任务,然后每隔period时间执行一次。
             */
    //        timer.schedule(task, new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2016-06-16 17:17:00"));
            timer.schedule(task,10000);
        }
    }

    示例:现在有两个任务A和B,没过5秒执行A,再过3秒执行B,如此交替循环执行。

    public class TimerTaskTest{
            private static Timer timer;
        
        public static void main(String []args ){
            timer = new Timer();
            timer.schedule(new A(), 5000);
        }
        //通过继承TimerTask类来编写任务
        static class A extends TimerTask {
            
            public void run() {
                System.out.println("hello");
                timer.schedule(new B(), 3000);
            }
        }
    
        static class B extends TimerTask {
            
            public void run() {
                System.out.println("world");
                timer.schedule(new A(), 5000);
            }
        }
    }

    在实际项目上用到较多Quartz是一个完全由Java编写的开源作业调度框架。

  • 相关阅读:
    <unittest学习8>unittest生成测试报告
    <unittest学习7>unittest的封装方法
    <unittest学习6>unittest多种加载用例方法
    <unittest学习5>unittest的几种执行方式和java的junit的很像
    <unittest学习4>跳过用例
    实验3.1
    I
    大数据运维---Zookeeper学习
    裸金属纳管
    一次Linux系统被攻击的分析过程
  • 原文地址:https://www.cnblogs.com/futiansu/p/5615921.html
Copyright © 2011-2022 走看看