• 七、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编写的开源作业调度框架。

  • 相关阅读:
    在Windows7下启动MongoDB服务的解决方案
    Spring MVC之@RequestBody, @ResponseBody 详解
    Spring MVC之@RequestParam @RequestBody @RequestHeader 等详解
    SpringMVC+Shiro权限管理
    Spring中@Async用法总结
    当spring 容器初始化完成后执行某个方法
    Java四种线程池的使用
    JavaWeb动态导出Excel可弹出下载
    kinderEditor + Struts2整合
    请求webservice接口的某方法数据
  • 原文地址:https://www.cnblogs.com/futiansu/p/5615921.html
Copyright © 2020-2023  润新知