2024年3月14日发(作者:)

用定时执行任务

1. 新建一个task 实现run方法

2. Timer t = new Time()

3. le(task );等等4个方法去执行

如果要在程序中定时执行任务,可以使用这个类实现。使用Timer类

需要一个继承了ask的类。TimerTask是一个虚类,需要实现它的run方

法,实际上是他implements了Runnable接口,而把run方法留给子类实现。

下面是我的一个例子:

class Worker extends TimerTask {

public void run() {

n("我在工作啦!");

}

}

Timer类用schedule方法或者scheduleAtFixedRate方法启动定时执行,schedule

重载了四个版本,scheduleAtFixedRate重载了两个。每个方法的实现都不同,下面是每

个方法的说明:

schedule

public void schedule(TimerTask task,

long delay)

Schedules the specified task for execution after the specified delay.

Parameters:

task - task to be scheduled.

delay - delay in milliseconds before task is to be executed.

Throws:

IllegalArgumentException - if delay is negative, or delay +

tTimeMillis() is negative.

IllegalStateException - if task was already scheduled or cancelled, or timer was

cancelled.

说明:该方法会在设定的延时后执行一次任务。