📜  Java Java类

📅  最后修改于: 2022-05-13 01:54:18.837000             🧑  作者: Mango

Java Java类

TimerTask 是Java.util 包中定义的一个抽象类。 TimerTask 类定义了一个任务,该任务可以安排为仅运行一次或重复运行多次。为了定义一个 TimerTask 对象,需要实现这个类并且需要重写 run 方法。当计时器对象安排它这样做时,会隐式调用 run 方法。

注意: TimerTask 类的实例用于定义需要定期运行的任务。

构造函数:

  • TimerTask() : 创建一个新的定时器任务

宣言:

public abstract class TimerTask
        extends Object
        implements Runnable

方法:

  • cancel(): Java.util.TimerTask.cancel()取消这个定时器任务
  • 句法:
public boolean cancel()
Returns:
true if this task is scheduled for one-time execution and
has not yet run, or this task is scheduled for repeated execution. 
Returns false if the task was scheduled for one-time 
execution and has already run, or if the task was never scheduled, 
or if the task was already cancelled.
  • run(): Java.util.TimerTask.run()这个定时器任务要执行的动作
  • 句法:
public abstract void run()
Description:
The action to be performed by this timer task
  • scheduleExecutionTime(): Java.util.TimerTask.scheduledExecutionTime()返回此任务最近一次实际执行的计划执行时间
  • 句法:
public long scheduledExecutionTime()
Returns: 
the time at which the most recent execution of this task was 
scheduled to occur, in the format returned by Date.getTime(). 
The return value is undefined if the task has yet to 
commence its first execution

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

  • 克隆
  • 等于
  • 敲定
  • 获取类
  • 哈希码
  • 通知
  • 通知所有
  • 到字符串
  • 等待

演示 TimerTask 类用法的Java程序

Java
// Java program to demonstrate
// working of TimerTask 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);
        if(i == 4)
        {
            synchronized(Test.obj)
            {
                Test.obj.notify();
            }
        }
    }
     
}
 
 
public class Test
{
    public static Test obj;
    public static void main(String[] args) throws InterruptedException
    {
        obj = new Test();
         
        // creating an instance of timer class
        Timer timer = new Timer();
         
        // creating an instance of task to be scheduled
        TimerTask task = new Helper();
         
        // scheduling the timer instance
        timer.schedule(task, 1000, 3000);
         
        // fetching the scheduled execution time of
        // the most recent actual execution of the task
        System.out.println(task.scheduledExecutionTime());
         
        synchronized(obj)
        {
            //this thread waits until i reaches 4
            obj.wait();
        }
         
        //canceling the task assigned
        System.out.println("Cancel the timer task: " + task.cancel());
         
        // at this point timer is still running
        // without any task assigned to it
     
        // canceling the timer instance created
        timer.cancel();
    }
}


输出:

1495715853591
Timer ran 1
Timer ran 2
Timer ran 3
Timer ran 4
Cancel the timer task: true

参考:

  • 甲骨文