Java定时执行代码

Linux大全评论3.7K views阅读模式

让我们需要定时执行的类继承自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).

企鹅博客
  • 本文由 发表于 2019年7月23日 00:01:25
  • 转载请务必保留本文链接:https://www.qieseo.com/146600.html

发表评论