linux 定时java,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.

说明:该方法会在指定的时间点执行任务,然后从该时间点开始,在设定的周期定时执行任务。特别的,如果设定的时间点在当前时间之前,任务会被马上执行,然后开始按照设定的周期定时执行任务。0b1331709591d260c1c78e86d0c51c18.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值