分为四个步骤
- 定义一个
java.util.concurrent.ScheduledExecutorService scheduledService
scheduledService = java.util.concurrent.Executors.newScheduledThreadPool(1)
- 定义
Runnable
scheduledService.scheduleAtFixedRate(Runnable, initDelay, period, TimeUnit unit)
示例代码
package com.yj.test.javaBases.testSchedule;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduleSayHello {
private ScheduledExecutorService scheduledService;
private Runnable runnable;
public ScheduleSayHello(){
scheduledService = Executors.newScheduledThreadPool(1);
runnable = new Runnable(){
@Override
public void run() {
System.out.println("helloworld");
}
};
}
public void test(){
scheduledService.scheduleAtFixedRate(runnable, 5, 3, TimeUnit.SECONDS);
}
public static void main(String[] args) {
new ScheduleSayHello().test();
}
}