Java定时执行代码


让我们需要定时执行的类继承自java.util.TimerTask中的TimerTask类,把需要执行的方法放入run方法中:

import java.util.TimerTask;

public class MyTimerTask extends TimerTask {
 
        @Override
     public void run() {
            System.out.println( " 备份程序运行…… " );
        }

}

然后我们是java.util.Timer类来执行这个方法,测试类:

import java.util.Timer;
 
public class Test {
 
     public static void main(String[] args) {
            Timer timer = new Timer();
            timer.schedule( new MyTimerTask(), 1000 );
 
        }
 
 }
 

我们看到控制台输出:

备份程序运行……


那么我们想让这个程序每隔五秒钟运行一次呢,可以这样来做:

timer.schedule( new MyTimerTask(), 0 , 5000 );
 

我们传入的第二个参数是方法首次执行时间,第三个参数是方法执行的间隔时间,我们可以在控制台看到:

备份程序运行……
备份程序运行……
备份程序运行……
备份程序运行……
 

当然我们也可以使用Date来实现定时操作:

Timer timer = new Timer();
Date date = new Date( 107 , 05 , 21 , 00 , 01 , 10 );
timer.schedule( new MyTimerTask(),date, 5000 );


public void schedule(TimerTask task,                     Date firstTime,                     long period)
Schedules the specified task for repeated fixed-delay execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.
In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well. In the long run, the frequency of execution will generally be slightly lower than the reciprocal of the specified period (assuming the system clock underlyingObject.wait(long) is accurate).

Fixed-delay execution is appropriate for recurring activities that require "smoothness." In other words, it is appropriate for activities where it is more important to keep the frequency accurate in the short run than in the long run. This includes most animation tasks, such as blinking a cursor at regular intervals. It also includes tasks wherein regular activity is performed in response to human input, such as automatically repeating a character as long as a key is held down.

Parameters:
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 time.getTime() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
说明:该方法会在指定的时间点执行任务,然后从该时间点开始,在设定的周期定时执行任务。特别的,如果设定的时间点在当前时间之前,任务会被马上执行,然后开始按照设定的周期定时执行任务。

相关内容