zoukankan      html  css  js  c++  java
  • Timer和TimerTask 定时器和定时任务

    这两个类使用起来非常方便,可以完成我们对定时器的绝大多数需求 

    Timer类是用来执行任务的类,它接受一个TimerTask做参数 

    Timer有两种执行任务的模式,最常用的是schedule,它可以以两种方式执行任务:1:在某个时间(Data),2:在某个固定的时间之后(int delay).这两种方式都可以指定任务执行的频率

    java.util.Timer定时器,实际上是个线程,定时调度所拥有的TimerTasks。


    一个TimerTask实际上就是一个拥有run方法的类,需要定时执行的代码放到run方法体内,TimerTask一般是以匿名类的方式创建。

    TimerTest.java:

    package com.cn;
    import java.io.IOException;
    import java.util.Timer;
      
    public class TimerTest{   
             
        public static void main(String[] args){   
            Timer timer = new Timer();   
            timer.schedule(new MyTask(), 1000, 2000);//在1秒后执行此任务,每次间隔2秒执行一次,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.   
            while(true){//这个是用来停止此任务的,否则就一直循环执行此任务   
                try{   
                    int in = System.in.read();  
                    if(in == 's'){   
                        timer.cancel();//使用这个方法退出任务   
                        break;
                    }   
                } catch (IOException e){   
                    // TODO Auto-generated catch block   
                    e.printStackTrace();   
                }   
            }   
        }  
        
        static class MyTask extends java.util.TimerTask{    
            public void run(){   
                System.out.println("________");   
            }   
        }  
    }
    

    此类运行时:

    程序启动1秒后在控制台打印“————”

    间隔两秒后接着执行MyTask的run()方法,打印“————”

    这样一直循环

    当在控制台输入s字符时,timer定时器取消工作

    跳出整个循环

    程序运行结束!

    Timer类的常用其他方法:

    cancel() 

    终止此计时器,丢弃所有当前已安排的任务。

    purge() 
    从此计时器的任务队列中移除所有已取消的任务。

    schedule(TimerTask task, Date time) 
    安排在指定的时间执行指定的任务。

    TimerTask类的常用其他方法:

    cancel() 
    取消此计时器任务。

    run() 
    此计时器任务要执行的操作。

    scheduledExecutionTime() 
    返回此任务最近实际 执行的已安排 执行时间。

    以下是几种调度task的方法:

    1.timer.schedule(task, time);  // time为Date类型:在指定时间执行一次。

    2.timer.schedule(task, firstTime, period);  // firstTime为Date类型,period为long。从firstTime时刻开始,每隔period毫秒执行一次。

    3.timer.schedule(task, delay)  // delay 为long类型:从现在起过delay毫秒执行一次

    4.timer.schedule(task, delay, period)  // delay为long,period为long:从现在起过delay毫秒以后,每隔period。毫秒执行一次。

  • 相关阅读:
    记录慕课学习爬取中国大学排名(由上交大计算的排名结果)
    SuperMap iMobile for Android室内导航APP
    Android studio入坑记录(SuperMap iMobile开发)
    2019年的十月和十一月
    python学习国庆期间
    学习python——collections系列
    又是快乐学习python的一天
    学习MATLAB
    Python学习练习题
    使用javaScript来实现一个有序链表
  • 原文地址:https://www.cnblogs.com/cxfly/p/10418160.html
Copyright © 2011-2022 走看看