java中Timer的scheduleAtFixedRate()函数的延迟和周期参数之间的差异

时间:2015-08-04 08:29:18

标签: java timertask

java.util.Timer.scheduleAtFixedRate(TimerTask timer, long delay, long period)中, delayperiod之间有什么区别?

2 个答案:

答案 0 :(得分:3)

对于这样的事情,总是看到(Java SDK)JavaDocs: https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html#scheduleAtFixedRate-java.util.TimerTask-long-long-

delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.

(您的IDE也应该自动显示给您)

所以延迟是从现在到第一次执行的时间,之后它再次执行每个期间毫秒。

查找的另一个好方法:为延迟期间使用两个不同的值,并使用TimerTask在控制台上打印一行。然后看看会发生什么。

答案 1 :(得分:0)

我们可以通过将 delay value (延迟值)作为sec / min传递给delay参数,来安排任务在更合适的时间启动任务。

运行RunTaskEvery2Seconds程序后,每6秒钟完成一次,该任务将被执行。 延迟的主要目的是延迟在首选时间执行的任务

package com.java.thread.task;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RunTaskEvery2Seconds {

public static void main(String[] args) {
    long timeIntervalForTaskOne = 2000;
    int delaySeconds = 6*1000;//6 seconds
    TimerTask taskOne = new TimerTask() {

        @Override
        public void run() {
//              log.info("Running Task One Time: {}", new Date());
                System.out.printf("Running Task One Time: %s", "call db", new Date() +"\n");
        }
    };

    Timer timer = new Timer();
    Calendar runningTime = Calendar.getInstance();
    System.out.printf("Running Task One -> Actual starting Time:%s", runningTime.getTime() +"\n");

    //updating delay time
    runningTime.setTimeInMillis(runningTime.getTimeInMillis() + delaySeconds);

    System.out.printf("Scheduled Running Task One will start at: %s", runningTime.getTime() +"\n");
    System.out.println("Waiting for Schedule of Running Task One");
    timer.scheduleAtFixedRate(taskOne, delaySeconds, timeIntervalForTaskOne);


}
}

控制台输出:

Running Task One -> Actual starting Time:Wed Mar 27 16:12:32 IST 2019
Scheduled Running Task One will start at: Wed Mar 27 16:12:38 IST 2019
Waiting for Schedule of Running Task One
Running Task One Time: Wed Mar 27 16:12:38 IST 2019
Running Task One Time: Wed Mar 27 16:12:40 IST 2019
Running Task One Time: Wed Mar 27 16:12:42 IST 2019