1. Timer
//实现TimerTask
public class MyTask1 extends TimerTask {
@Override
public void run() {
System.out.println("任务1执行 ");
}
}
测试:
public class Test {
public static void main(String[] args) {
Timer timer = new Timer();
/*延迟1s*/
timer.schedule(new MyTask1(),1000,1000);
}
}
具体使用有: 方法名相同 形参列表不同 方法重载
在特定时间执行任务 只执行一次 | public void schedule(TimerTask task,Date time) |
在特定时间之后执行 只执行一次 | public void schedule(TimerTask task,long delay) |
指定第一次执行时间 之后按照间隔 重复执行 | public void schedule(TimerTask task,Date firstTime,long period) |
特定延迟之后第一次执行,然后按照间隔时间,重复执行 | public void schedule(TimerTask task,long delay,long period) |
第一次执行之后,特定频率执行,与3相同 | public void scheduleAtFixedRate(TimerTask task,Date firstTime,long period) |
在delay毫秒之后第一次执行,后按照特定频率执行 | public void scheduleAtFixedRate(TimerTask task,long delay,long period) |
delay : 延迟执行的毫秒数 在delay毫秒之后第一次 执行
period 重复执行的时间间隔
2. Spring Task
2.1 开启定时任务支持
在启动类似使用@EnableSchduling
@EnableScheduling
public class App {
}
2.2 同步定时任务
在方法上添加#@schduled注解 注意定时任务所在的类要放在 ioc 容器中 @Commponent
@Component
@Slf4j
public class ScheduledTask {
/*定时任务*/
}
fixedDelay = 5000
上一次开始执行时间到下一次开始时间间隔为 5s
/*定时任务*/
@Scheduled(fixedDelay = 5000)
public void fixedDelay(){
log.info("fixedDelay: 上次结束到下次开始执行时间间隔 5s");
}
fixedRate = 5000
上次开始执行时间 下次开始时间为5s
/*定时任务*/
@Scheduled(fixedRate = 5000)
public void fixedRate (){
log.info("fixedDelay: 上一次开始执行时间 到下一次开始时间间隔为 5s");
}
initiaDelay = 6000 , fixedDelay =2000
第一次延迟六秒执行 之后每间隔2s执行
/*定时任务*/
@Scheduled(initialDelay = 6000,fixedDelay = 2000)
public void initialDelay (){
log.info("initialDelay: 第一次延迟六秒执行 之后每次间隔2s执行");
}
2.3 使用cron表达式 重点
cron = " "
/*定时任务*/
@Scheduled(cron = "0/5 * * * * ?")
public void cron (){
log.info("表达式为每间5秒执行");
}
Quatz 表达式生产器:
软件包:https://wwxc.lanzouo.com/iNU5X27ulklc
密码:hcej
2.4 线程池
1.配置线程池
@Component
public class ExecutorConfig {
//定义核心线程数
public static final int CORE_POOL_SIZE = 10;
//最大线程数
public static final int MAX_POOL_SIZE = 20;
//任务队列容量大小
public static final int QUEUE_MAX_COUNT = 100;
@Bean("asyncScheduledPool")
public Executor asyncScheduledPool(){
/*自定义参数*/
ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();
threadPoolExecutor.setCorePoolSize(CORE_POOL_SIZE);
threadPoolExecutor.setMaxPoolSize(MAX_POOL_SIZE);
threadPoolExecutor.setQueueCapacity(QUEUE_MAX_COUNT);
threadPoolExecutor.setThreadNamePrefix("myTask_");
/*执行拒绝策略*/
threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
return threadPoolExecutor;
}
}
2.开启异步支持
@SpringBootApplication
@EnableScheduling
//开启异步支持
@EnableAsync
public class App {
3. 定义异步方法
在方法名上 使用@Async 开启异步
/*定时任务*/
@Scheduled(cron = "0/1 * * * * ?")
@Async("asyncScheduledPool")
public void cron (){
log.info("task执行了,{}",Thread.currentThread().getName());
}