Java定时任务实现
由于工作中用到定时任务,在csdn首页上又恰巧看到关于定时任务的文章,写的不错,本人只是抱着学习的态度!
定时任务的实现:
普通thread实现,
TimerTask实现,
ScheduledExecutorService实现
Thread方式实现:
public void threadWay(){
final long timeInterval = 5000;
Runnable run = new Runnable() {// 任务
public void run() {
while (true) {
System.out.println("hello world!");
try {
Thread.sleep(timeInterval);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
};
Thread thread = new Thread(run);
thread.start();// 启动Thread
}
这是最基础的实现定时任务的方式!
TimerTask方式实现:
public void timeTaskWay(){
TimerTask timeTask = new TimerTask(){
public void run(){
System.out.println("hello world");
}
};
Timer time = new Timer();
long delay = 10000;
long intervalPeriod = 3*1000;
time.scheduleAtFixedRate(timeTask, delay, intervalPeriod);
}
这种方式较高级,能够设置delay(延迟时间),intervalPerid(运行间隔)
ScheduledExecutorService方式实现:
public void scheduledExecutorServiceWay() {
Runnable run = new Runnable() {
public void run() {
System.out.println("hello world");
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(run, 0, 10, TimeUnit.SECONDS);
}
这种方式稍微高级点。
这是Java Application中,实现定时的任务的方式,如果使用的Spring可以用quartz实现,通过配置的实现,能够设置更多的参数!
原文地址:http://blog.csdn.net/qq405371160/article/details/23696525