在ScheduledExecutorService接口中可以看到:
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
command:执行线程
initialDelay:初始化延时即首次执行的延时时间
period:两次开始执行最小间隔时间即定时执行的间隔时间
unit:计时单位
// 将任务放入定时服务中 // scheduleAtFixedRate:固定的频率来执行某项计划,它不受计划执行时间的影响。到时间,它就执行。 // scheduleWithFixedDelay:按照相对固定频率来执行,相对是相对任务的。即无论某个任务执行多长时间,等执行完了,再延迟指定的时间执行下一次任务,它受上一次计划执行时间的影响
使用scheduleAtFixedRate()方法实现周期性执行
初始化延迟0ms开始执行,每隔100ms重新执行一次任务
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TestScheduledExecutorService {
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool();
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("run "+ System.currentTimeMillis());
}
}, 0, 100, TimeUnit.MILLISECONDS);
}
使用scheduleAtFixedRate()方法实现周期性定时任务(设定每天某个时刻执行)
比如我们的需求:需要在每天的夜里12点执行定时任务
public class TestScheduledExecutorService {
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool();
long oneDay = 24 * 60 * 60 * 1000;
long initDelay = getTimeMillis("24:00:00")-System.currentTimeMillis();
initDelay = initDelay > 0 ?initDelay:oneDay+initDelay;
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("run "+ System.currentTimeMillis());
}
}, initDelay, oneDay, TimeUnit.MILLISECONDS);
}
/*
* 获取指定时间对应的毫秒数
* @param time "HH:mm:ss"
* @return
*/
private static long getTimeMillis(String time) {
try {
DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
java.util.Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);
return curDate.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}