2018年7月6日20:05:08
【1】隶属于 java.util.Timer
void | scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
Schedules the specified task for repeated
fixed-rate execution, beginning at the specified time.
|
void | scheduleAtFixedRate(TimerTask task, long delay, long period)
Schedules the specified task for repeated
fixed-rate execution, beginning after the specified delay.
|
【2】方法定义
2.1 设定延迟时间
public void scheduleAtFixedRate(TimerTask task, long delay, long period)Parameters:
task
- task to be scheduled.
delay
- delay in milliseconds before task is to be executed.
period
- time in milliseconds between successive task executions.
2.2 设定开始
public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)Parameters:
task
- task to be scheduled.
firstTime
- First time at which task is to be executed.
period
- time in milliseconds between successive task executions.
【3】另外介绍一个线程类Timer,它是执行定时任务的:TimerTask及其常用方法
【4】
4.1 Test01
设定定时任务执行的最早开始时间,同时也设置任务的定时执行间隔
package Timer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class scheduleAtFixedRateTest {
public static void main(String[] args) throws ParseException {
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Date startDate = dateFormatter.parse("2019/07/06 00:20:00"); //现在是18年,故线程不会被执行
Date startDate = dateFormatter.parse("2018/07/06 00:20:00"); //现在是18年,线程会被执行
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
public void run()
{
System.out.println("execute task!" + this.scheduledExecutionTime());
}
},startDate,1000);
}
}
输出结果:
execute task!1530880389000
execute task!1530880390000
4.2 Test02
设定固定的延时间隔,同时也设置任务的定时执行间隔
package Timer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class scheduleAtFixedRateTest {
public static void main(String[] args) {
Timer timer = new Timer();
System.out.println("current time: "+System.currentTimeMillis());
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("delay 1000ms to print.."+this.scheduledExecutionTime());
}
},10000, 1000);
}
}
输出结果:【可见任务的执行延迟了10*1000ms】
current time: 1530881018274
delay 1000ms to print..1530881028274
delay 1000ms to print..1530881029274
【5】现实场景与解释
5.1
商业代码,通过线程池来执行定时任务,而非Timer定时器...
5.2
用反射机制来获取线程池的bean...
5.3
瞅瞅线程池类里面长什么样,发现包含了一个ScheduledThreadPoolExecutor....
5.4
这个ScheduledThreadPoolExecutor来头不小,继承了线程池ThreadPoolExecutor,
同时还实现了ScheduledExecutorService;
5.5
ThreadPoolExecutor
ScheduledExecutorService
确认过眼神,这是个有意思的东西,,,,
未完...........