import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
*设置周期执行的方法
*/
class Temp extends Thread{
public void run(){
System.out.println("run");
}
}
/**
*开始周期执行
*/
public class Test{
public static void main(String args[]) throws Exception{
Temp command = new Temp();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> scheduleTask = scheduler.scheduleWithFixedDelay(command, 2, 3, TimeUnit.SECONDS);
}
}
/**
* 改变周期
* This method will reschedule "command" with the new param time
*/
public void changeReadInterval(long time)
{
if(time > 0){
if (futureTask != null){
futureTask.cancel(true);
}
futureTask = scheduledExecutorService.scheduleAtFixedRate(command, 0, time, TimeUnit.SECONDS);
}
}
ScheduledExecutorService 和 ScheduledFuture 类用法
最新推荐文章于 2023-11-16 16:36:19 发布