Java如何实现定时执行的任务?
- 内容介绍
- 文章标签
- 相关推荐
本文共计307个文字,预计阅读时间需要2分钟。
Java定时任务实现方式一般有三种:Thread实现、TimerTask实现、ScheduledExecutorService实现。以下是Thread实现的方法示例(不推荐):
javapublic static void threadTask() { // run in a second final long time=1000; new Thread(() -> { try { Thread.sleep(time); // 任务执行代码 } catch (InterruptedException e) { e.printStackTrace(); } }).start();}
Java定时任务de实现一般有三种方法:thread实现、TimerTask实现、ScheduledExecutorService实现三种。
1 thread实现(不建议)
public static void threadTask(){
// run in a second
final long timeInterval = 1000;
Runnable runnable = new Runnable() {
public void run() {
while (true) {
// run task
System.out.println("Run Task ...... ");
try {
Thread.sleep(timeInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread = new
2 TimerTask实现
可以控制任务启动和取消,可以设置第一次任务运行的delay时间。
TimerTask task = new TimerTask(){
public void run() {
// run task
System.out.println("Run Task ...... ");
}
};
Timer timer = new Timer();
long delay = 0;
long intevalPeriod = 1 * 1000;
//timer.scheduleAtFixedRate(task, delay,intevalPeriod);
timer.scheduleAtFixedRate(task, new
3 ScheduledExecutorService实现
通过线程池的方式来执行任务,可以设定第一次运行任务delay时间,较好的时间间隔约定。
Runnable runnable = new Runnable() {
public void run() {
// run task
System.out.println("Run Task ...... ");
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
service.scheduleWithFixedDelay(runnable, 0, 1, TimeUnit.SECONDS);
}
本文共计307个文字,预计阅读时间需要2分钟。
Java定时任务实现方式一般有三种:Thread实现、TimerTask实现、ScheduledExecutorService实现。以下是Thread实现的方法示例(不推荐):
javapublic static void threadTask() { // run in a second final long time=1000; new Thread(() -> { try { Thread.sleep(time); // 任务执行代码 } catch (InterruptedException e) { e.printStackTrace(); } }).start();}
Java定时任务de实现一般有三种方法:thread实现、TimerTask实现、ScheduledExecutorService实现三种。
1 thread实现(不建议)
public static void threadTask(){
// run in a second
final long timeInterval = 1000;
Runnable runnable = new Runnable() {
public void run() {
while (true) {
// run task
System.out.println("Run Task ...... ");
try {
Thread.sleep(timeInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread = new
2 TimerTask实现
可以控制任务启动和取消,可以设置第一次任务运行的delay时间。
TimerTask task = new TimerTask(){
public void run() {
// run task
System.out.println("Run Task ...... ");
}
};
Timer timer = new Timer();
long delay = 0;
long intevalPeriod = 1 * 1000;
//timer.scheduleAtFixedRate(task, delay,intevalPeriod);
timer.scheduleAtFixedRate(task, new
3 ScheduledExecutorService实现
通过线程池的方式来执行任务,可以设定第一次运行任务delay时间,较好的时间间隔约定。
Runnable runnable = new Runnable() {
public void run() {
// run task
System.out.println("Run Task ...... ");
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
service.scheduleWithFixedDelay(runnable, 0, 1, TimeUnit.SECONDS);
}

