写代码的时候有些任务需要做周期处理,例如每天9点解析文件并落地到数据库。这时候就需要选择合适的任务调度策略。以下是java里常用的几个任务调度方法:
1、java.util.Timer, java.util.TimerTask
timer启动一个异步线程执行任务,周期执行任务策略对应方法scheduleAtFixedRate(TimerTask task, long delay, long period),scheduleAtFixedRate(TimerTask task, Date firstTime, long period)可以指定首次任务时间和周期间隔时间。停止任务执行使用cancel()。
Timer执行任务是单线程的,内部用任务队列来维护待执行任务,任务使用最小堆算法排序(任务下次执行时间距今越小越优先被执行),添加任务时使用锁机制防止并发问题。但是如果自定义的任务处理逻辑包含访问竞争资源,则需要自己进行相关竞争资源的防并发处理。
final AtomicInteger taskExecuteCnt = new AtomicInteger();
TimerTask timerTaskA = new TimerTask() {
@Override
public void run() {
// scheduler work content
if (taskExecuteCnt.get() >= 10) {
timer.cancel();
}
System.out.printf("Task A execute,current time:%s\n", new Date());
taskExecuteCnt.incrementAndGet();
}
};
TimerTask timerTaskB = new TimerTask() {
@Override
public void run() {
// scheduler work content
if (taskExecuteCnt.get() >= 10) {
timer.cancel();
}
System.out.printf("Task B execute,current time:%s\n", new Date());
taskExecuteCnt.incrementAndGet();
}
};
timer.scheduleAtFixedRate(timerTaskA, 0, 500);
timer.scheduleAtFixedRate(timerTaskB, 0, 500);
执行后结果:
Task A execute,current time:Mon Sep 28 14:08:21 CST 2015
Task B execute,current time:Mon Sep 28 14:08:21 CST 2015
Task B execute,current time:Mon Sep 28 14:08:22 CST 2015
Task A exe
1、java.util.Timer, java.util.TimerTask
timer启动一个异步线程执行任务,周期执行任务策略对应方法scheduleAtFixedRate(TimerTask task, long delay, long period),scheduleAtFixedRate(TimerTask task, Date firstTime, long period)可以指定首次任务时间和周期间隔时间。停止任务执行使用cancel()。
Timer执行任务是单线程的,内部用任务队列来维护待执行任务,任务使用最小堆算法排序(任务下次执行时间距今越小越优先被执行),添加任务时使用锁机制防止并发问题。但是如果自定义的任务处理逻辑包含访问竞争资源,则需要自己进行相关竞争资源的防并发处理。
示例代码如下:
final Timer timer = new Timer();final AtomicInteger taskExecuteCnt = new AtomicInteger();
TimerTask timerTaskA = new TimerTask() {
@Override
public void run() {
// scheduler work content
if (taskExecuteCnt.get() >= 10) {
timer.cancel();
}
System.out.printf("Task A execute,current time:%s\n", new Date());
taskExecuteCnt.incrementAndGet();
}
};
TimerTask timerTaskB = new TimerTask() {
@Override
public void run() {
// scheduler work content
if (taskExecuteCnt.get() >= 10) {
timer.cancel();
}
System.out.printf("Task B execute,current time:%s\n", new Date());
taskExecuteCnt.incrementAndGet();
}
};
timer.scheduleAtFixedRate(timerTaskA, 0, 500);
timer.scheduleAtFixedRate(timerTaskB, 0, 500);
执行后结果:
Task A execute,current time:Mon Sep 28 14:08:21 CST 2015
Task B execute,current time:Mon Sep 28 14:08:21 CST 2015
Task B execute,current time:Mon Sep 28 14:08:22 CST 2015
Task A exe