代码结构:
.
|____Main.java
|____ScheduledThreadPoolExecutorMgr.java
|____Main.java
package scheduledthreadpoolexecutortest;
import java.util.concurrent.RunnableScheduledFuture;
public class Main {
public static int count = 0;
public static RunnableScheduledFuture runnable;
public static void main(String[] args) {
long start = System.currentTimeMillis();
runnable = ScheduledThreadPoolExecutorMgr.schedule(new Runnable() {
@Override
public void run() {
count++;
System.out.println("第" + count + "次运行" + " " + Thread.currentThread().getName() + " 在 " + (System.currentTimeMillis() - start) + " ms后");
}
}, 0, 1);
ScheduledThreadPoolExecutorMgr.scheduleOnce(new Runnable() {
@Override
public void run() {
System.out.println("cancel");
ScheduledThreadPoolExecutorMgr.cancel(runnable);
}
}, 3);
}
}
/*
第1次运行 pool-1-thread-1 在 9 ms后
第2次运行 pool-1-thread-2 在 1010 ms后
第3次运行 pool-1-thread-3 在 2011 ms后
第4次运行 pool-1-thread-1 在 3011 ms后
cancel
*/
|____ScheduledThreadPoolExecutorMgr.java
package scheduledthreadpoolexecutortest;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ScheduledThreadPoolExecutorMgr {
// 任务线程池
private static ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors());
/**
* 定时任务
*
* @param runnable 执行的任务
* @param initDelayTimeSec 初始延迟多久
* @param everyTimeSec 每次间隔多久
* @return
*/
public static RunnableScheduledFuture schedule(Runnable runnable, int initDelayTimeSec, int everyTimeSec) {
ScheduledFuture<?> scheduledFuture = scheduled.scheduleAtFixedRate(runnable, initDelayTimeSec, everyTimeSec, TimeUnit.SECONDS);
return (RunnableScheduledFuture) scheduledFuture;
}
/**
* 只执行一次的任务
*
* @param runnable 执行的任务
* @param initDelayTimeSec 延迟多少秒开始执行
* @return
*/
public static RunnableScheduledFuture scheduleOnce(Runnable runnable, int initDelayTimeSec) {
ScheduledFuture<?> schedule = scheduled.schedule(runnable, initDelayTimeSec, TimeUnit.SECONDS);
return (RunnableScheduledFuture) schedule;
}
/**
* 取消一个任务
*/
public static void cancel(RunnableScheduledFuture runnable) {
scheduled.remove(runnable);
}
/**
* 关闭定时任务
*/
public static void shutdown() {
scheduled.shutdown();
}
}
来源:oschina
链接:https://my.oschina.net/u/4350688/blog/4477297