1、JDK5.ScheduledExecutorService
2、代码实现
package cn
.enjoy
.jobs
.feiji
;
import org
.junit
.Test
;
import java
.util
.concurrent
.Executors
;
import java
.util
.concurrent
.ScheduledExecutorService
;
import java
.util
.concurrent
.TimeUnit
;
public class Demo03 {
@Test
public void test1() throws InterruptedException
{
ScheduledExecutorService service
= Executors
.newScheduledThreadPool(1);
service
.scheduleAtFixedRate(new Runnable() {
int x
= 0;
@Override
public void run() {
System
.out
.println(Thread
.currentThread().getId()+"-- and x = "+x
);
}
}, 1, 1, TimeUnit
.SECONDS
);
Thread
.sleep(Integer
.MAX_VALUE
);
}
@Test
public void test2() throws InterruptedException
{
Runnable r
= new Runnable() {
int x
= 0;
@Override
public void run() {
System
.out
.println(Thread
.currentThread().getId()+"-- and x = "+x
);
}
};
Runnable r2
=new Runnable() {
int x
= 0;
@Override
public void run() {
try {
Thread
.sleep(5000);
} catch (InterruptedException e
) {
e
.printStackTrace();
}
System
.out
.println(Thread
.currentThread().getId()+"-- and x = "+x
);
}
};
ScheduledExecutorService service
= Executors
.newScheduledThreadPool(2);
service
.scheduleAtFixedRate(r
, 1, 1, TimeUnit
.SECONDS
);
service
.scheduleAtFixedRate(r2
, 1, 2, TimeUnit
.SECONDS
);
Thread
.sleep(Integer
.MAX_VALUE
);
}
@Test
public void test3() throws InterruptedException
{
Runnable r
= new Runnable() {
int x
= 0;
@Override
public void run() {
System
.out
.println(Thread
.currentThread().getId()+"-- and x = "+x
);
}
};
Runnable r2
=new Runnable() {
int x
= 0;
@Override
public void run() {
System
.out
.println(Thread
.currentThread().getId()+"-- and x = "+x
);
int i
= 10/0;
}
};
ScheduledExecutorService service
= Executors
.newScheduledThreadPool(2);
service
.scheduleAtFixedRate(r
, 1, 1, TimeUnit
.SECONDS
);
Thread
.sleep(Integer
.MAX_VALUE
);
}
}
3、cron表达式
4、Spring&SpringBoot任务调度工具
package com
.cc
.timer
.springtask
;
import org
.slf4j
.Logger
;
import org
.slf4j
.LoggerFactory
;
import org
.springframework
.scheduling
.annotation
.Async
;
import org
.springframework
.scheduling
.annotation
.Scheduled
;
import org
.springframework
.stereotype
.Component
;
import java
.time
.LocalDateTime
;
@Component
public class SpringTaskDemo {
private static final Logger log
= LoggerFactory
.getLogger(SpringTaskDemo
.class);
@Scheduled(cron
= "0/1 * * * * *")
public void scheduled1() throws InterruptedException
{
log
.info("scheduled1 每1秒执行一次:{}", LocalDateTime
.now());
}
@Scheduled(fixedRate
= 1000)
public void scheduled2() throws InterruptedException
{
log
.info("scheduled2 每1秒执行一次:{}", LocalDateTime
.now());
}
@Scheduled(fixedDelay
= 3000)
public void scheduled3() throws InterruptedException
{
log
.info("scheduled3 上次执行完毕后隔3秒继续执行:{}", LocalDateTime
.now());
}
}
上一章:任务调度(一):线程/TimerTask/Timer 下一章:任务调度(三):Quartz