- 1
- 2
- 3
- 4
- 5
- 6
Java实现定时任务方式
1.Thread
public class Demo01 {
static long count = 0;
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
count++;
System.out.println(count);
} catch (Exception e) {
// TODO: handle exception
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
2.TimerTask
/**
* 使用TimerTask类实现定时任务
*/
public class Demo02 {
static long count = 0;
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
count++;
System.out.println(count);
} catch (Exception e) {
// TODO: handle exception
}
}
}
};
Timer timer = new Timer();
// 天数
long delay = 0;
// 秒数
long period = 1000;
timer.scheduleAtFixedRate(timerTask, delay, period);
}
}
tomcat7:run
-Denv=dev -Ddev_meta=http://192.168.1.204:8801/
轮询: 支持集群
鼓掌转移: 如果2台服务器。一个故障停止,接下来的服务都会在剩下的服务器执行。保证 整体正常运行。