当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Java.util.Timer用法及代码示例


Timer 类提供了一个方法调用,线程使用该方法调用来安排任务,例如在某个常规时间点后运行一段代码。每个任务可以安排运行一次或重复执行多次。每个计时器对象都与一个后台线程关联,该后台线程负责执行计时器对象的所有任务。
笔记:

  • Timer 类是线程安全的。
  • Timer 类使用二进制堆数据结构来存储其任务。

构造函数:

  • Timer():创建一个新的计时器
  • 计时器(布尔 isDaemon):创建一个新的计时器,其关联的线程可以指定为守护进程运行
  • 计时器(字符串名称):创建一个新的计时器,其关联的线程具有指定的名称
  • 计时器(字符串名称,布尔值 isDaemon):创建一个新的计时器,其关联的线程具有指定的名称,并且可以指定为作为守护进程运行

声明:

public class Timer
        extends Object

从类 java.lang.Object 继承的方法

  • clone
  • equals
  • finalize
  • getClass
  • hashCode
  • notify
  • notifyAll
  • toString
  • wait

方法:

  • cancel(): java.util.Timer.cancel()终止此计时器,丢弃所有当前计划的任务。不干扰当前正在执行的任务(如果存在)。一旦计时器终止,其执行线程就会正常终止,并且不能在其上调度更多任务
    用法:
public void cancel()
  • purge(): java.util.Timer.purge()从此计时器的任务队列中删除所有已取消的任务
    用法:
public int purge()
返回:
the number of tasks removed from the queue
  • 时间表(TimerTask任务,日期时间):java.util.Timer.schedule(TimerTask任务,日期时间)安排指定的任务在指定的时间执行
    用法:
public void schedule(TimerTask task, Date time)
参数:
task - task to be scheduled.
time - time at which task is to be executed.
Throws:
IllegalArgumentException - if time.getTime() is negative.
IllegalStateException - if the task was already scheduled or cancelled, 
the timer was cancelled, or timer thread terminated.
NullPointerException - if task or time is null
  • 时间表(TimerTask任务,日期firstTime,长周期):java.util.Timer.schedule(TimerTask任务,日期firstTime,长周期)安排指定任务从指定时间开始重复执行fixed-delay
    用法:
public void schedule(TimerTask task, Date firstTime, long period)
参数:
task - task to be scheduled.
firstTime - First time at which task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if firstTime.getTime() < 0,
 or period <= 0
IllegalStateException - if task was already scheduled 
or cancelled, timer was cancelled, 
or timer thread terminated.
NullPointerException - if task or firstTime is null

Java


// Java program to demonstrate
//schedule method calls of Timer class
import java.util.Timer;
import java.util.TimerTask;
class Helper extends TimerTask
{
    public static int i = 0;
    public void run()
    {
        System.out.println("Timer ran " + ++i);
    }
}
public class Test
{
    public static void main(String[] args)
    {
         
        Timer timer = new Timer();
        TimerTask task = new Helper();
         
        timer.schedule(task, 2000, 5000);
         
    }
}

输出:

Timer ran 1
Timer ran 2
Timer ran 3
Timer ran 4
Timer ran 5
.
.
.
  • Schedule(TimerTask任务,长延迟):java.util.Timer.schedule(TimerTask任务,长延迟)安排指定的任务在指定的延迟后执行
    用法:
public void schedule(TimerTask task, long delay)
参数:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
Throws:
IllegalArgumentException - if delay is negative,
or delay + System.currentTimeMillis() is negative.
IllegalStateException - if a task was already scheduled 
or cancelled, the timer was cancelled, 
or timer thread terminated.
NullPointerException - if task is null
  • Schedule(TimerTask任务,长延迟,长周期):java.util.Timer.schedule(TimerTask任务,长延迟,长周期)安排指定的任务重复执行fixed-delay,在指定的延迟后开始用法:
public void schedule(TimerTask task, long delay, long period)
参数:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if delay < 0, 
or delay + System.currentTimeMillis() < 0, or 
period <= 0
IllegalStateException - if task was already scheduled 
or cancelled, timer was cancelled, 
or timer thread terminated.
NullPointerException - if task is null
  • ScheduleAtFixedRate(TimerTask任务,日期firstTime,长周期):java.util.Timer.scheduleAtFixedRate(TimerTask任务,日期firstTime,长周期)安排指定任务从指定时间开始重复执行fixed-rate用法:
public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
参数:
task - task to be scheduled.
firstTime - First time at which task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if firstTime.getTime() <
0 or period <= 0
IllegalStateException - if task was already scheduled
 or cancelled, timer was cancelled, 
or timer thread terminated.
NullPointerException - if task or firstTime is null
  • ScheduleAtFixedRate(TimerTask任务,长延迟,长周期):java.util.Timer.scheduleAtFixedRate(TimerTask任务,长延迟,长周期)安排指定的任务重复执行fixed-rate,在指定的延迟后开始用法:
public void scheduleAtFixedRate(TimerTask task, long delay, long period)
参数:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if delay < 0, 
or delay + System.currentTimeMillis() < 0, or 
period <= 0
IllegalStateException - if task was already 
scheduled or cancelled, timer was cancelled, 
or timer thread terminated.
NullPointerException - if task is null

Java


// Java program to demonstrate
// scheduleAtFixedRate method of Timer class
import java.util.Timer;
import java.util.TimerTask;
import java.util.*;
class Helper extends TimerTask
{
    public static int i = 0;
    public void run()
    {
        System.out.println("Timer ran " + ++i);
        if(i == 4)
        {
            synchronized(Test.obj)
            {
                Test.obj.notify();
            }
        }
    }
     
}
public class Test
{
    protected static Test obj;
    public static void main(String[] args) throws InterruptedException
    {
        obj = new Test();
         
        //creating a new instance of timer class
        Timer timer = new Timer();
        TimerTask task = new Helper();
        //instance of date object for fixed-rate execution
        Date date = new Date();
        timer.scheduleAtFixedRate(task, date, 5000);
         
        System.out.println("Timer running");
        synchronized(obj)
        {
            //make the main thread wait
            obj.wait();
             
            //once timer has scheduled the task 4 times, 
            //main thread resumes
            //and terminates the timer
            timer.cancel();
             
            //purge is used to remove all cancelled 
            //tasks from the timer'stack queue
            System.out.println(timer.purge());
        }
    }
}

输出:

Timer running
Timer ran 1
Timer ran 2
Timer ran 3
Timer ran 4
0

参考:



相关用法


注:本文由纯净天空筛选整理自佚名大神的英文原创作品 Java.util.Timer Class in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。