ScheduledExecutorService定时任务的使用
2014-03-20 12:23
399 查看
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class ScheduledExecutorServiceTest
{
public static void main(String[] args) throws InterruptedException,ExecutionException
{
//*创建线程池
ScheduledExecutorService service=Executors.newScheduledThreadPool(2);
//*创建要执行的线程代码
Runnable task=new Runnable()
{
public void run()
{
System.out.println("Taskrepeating.");
}
};
//*执行定时线程操作。 task--线程任务 1--启动后首次执行时间 1---之后每次间隔时间 TimeUnit.SECONDS ---时间单位
final ScheduledFuture future1=service.scheduleAtFixedRate(task,1,1,TimeUnit.SECONDS);
//*
ScheduledFuture future2=service.schedule(new Callable()
{
public String call()
{
future1.cancel(true);
return "taskcancelled!";
}
},10,TimeUnit.SECONDS);
System.out.println(future2.get());
//*5
service.shutdown();
}
}
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class ScheduledExecutorServiceTest
{
public static void main(String[] args) throws InterruptedException,ExecutionException
{
//*创建线程池
ScheduledExecutorService service=Executors.newScheduledThreadPool(2);
//*创建要执行的线程代码
Runnable task=new Runnable()
{
public void run()
{
System.out.println("Taskrepeating.");
}
};
//*执行定时线程操作。 task--线程任务 1--启动后首次执行时间 1---之后每次间隔时间 TimeUnit.SECONDS ---时间单位
final ScheduledFuture future1=service.scheduleAtFixedRate(task,1,1,TimeUnit.SECONDS);
//*
ScheduledFuture future2=service.schedule(new Callable()
{
public String call()
{
future1.cancel(true);
return "taskcancelled!";
}
},10,TimeUnit.SECONDS);
System.out.println(future2.get());
//*5
service.shutdown();
}
}
相关文章推荐
- java使用ScheduledExecutorService定时任务
- 使用ScheduledExecutorService周期性的定时任务
- Java 定时任务 ScheduledExecutorService 的使用
- ScheduledExecutorService定时周期执行指定的任务 ,关于scheduleAtFixedRate 和 scheduleWithFixedDelay使用区别
- Spring定时任务的实现方式--ScheduledExecutorService and ScheduledExecutorFactoryBean的简单源码解析以及使用
- 【转】java定时任务接口ScheduledExecutorService
- 定时任务实现Timer, TimeTask, ScheduledExecutorService及Spring定时器
- ScheduledExecutorService执行周期性或定时任务
- ScheduledExecutorService定时周期执行指定的任务
- 定时任务实现Timer, TimeTask, ScheduledExecutorService及Spring定时器
- ScheduledExecutorService定时周期执行指定的任务
- ScheduledExecutorService执行定时任务
- ScheduledExecutorService执行周期性或定时任务
- ScheduledExecutorService定时周期执行指定的任务
- ScheduledExecutorService定时周期执行指定的任务
- ScheduledExecutorService执行定时任务
- ScheduledExecutorService执行周期性或定时任务
- Java并发定时任务调度之Timer和ScheduledExecutorService
- Jdk自带的定时任务TimerTask和ScheduledExecutorService及其在Spring中的集成
- ScheduledExecutorService定时周期执行指定的任务