项目源码
1.SpringTask
SpringTask是Spring自主研发的轻量级定时任务工具,相比于Quartz更加简单方便,且不需要引入其他依赖即可使用。
2.Cron表达式
cron是一个表达时间的表达式,在SpringTask中可以用于指定任务的执行时间. 网上直接生产你所指定的时间 详细语法参照
3. springtask的配置
只需要在配置类中添加一个@EnableScheduling注解即可开启SpringTask的定时任务能力
@Configuration
@EnableScheduling
public class SpringTaskConfig {
@Bean
public TaskScheduler
taskScheduler() {
ThreadPoolTaskScheduler scheduler
= new ThreadPoolTaskScheduler();
scheduler
.setPoolSize(3);
return scheduler
;
}
}
4.cron定时任务
@Component
public class OrderTimeOutCancelTask {
private Logger LOGGER
= LoggerFactory
.getLogger(OrderTimeOutCancelTask
.class);
private static final SimpleDateFormat format
= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:sss");
@Scheduled(cron
= "0/15 * * * * ? ")
private void sayHello(){
String dateTime
= format
.format(new Date());
LOGGER
.info("{} 向宇宙发出了一声问候: Hello World!", dateTime
);
try {
Thread
.sleep(10000);
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}
@Scheduled(cron
= "0/16 * * * * ? ")
private void sayHello2(){
String dateTime
= format
.format(new Date());
LOGGER
.info("{} 向宇宙发出了一声问候: 你好,世界", dateTime
);
}
}
5. 固定速率执行、固定延迟执行、初始延迟执行
@Component
public class ScheduledTasks {
private static final Logger log
= LoggerFactory
.getLogger(ScheduledTasks
.class);
private static final SimpleDateFormat dateFormat
= new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate
= 5000)
public void reportCurrentTimeWithFixedRate() {
log
.info("Current Thread : {}", Thread
.currentThread().getName());
log
.info("Fixed Rate Task : The time is now {}", dateFormat
.format(new Date()));
}
@Scheduled(fixedDelay
= 2000)
public void reportCurrentTimeWithFixedDelay() {
try {
TimeUnit
.SECONDS
.sleep(3);
log
.info("Fixed Delay Task : The time is now {}", dateFormat
.format(new Date()));
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}
@Scheduled(initialDelay
= 5000, fixedRate
= 5000)
public void reportCurrentTimeWithInitialDelay() {
log
.info("Fixed Rate Task with Initial Delay : The time is now {}", dateFormat
.format(new Date()));
}
@Scheduled(cron
= "1-2 * * * * ? ")
public void reportCurrentTimeWithCronExpression() {
log
.info("Cron Expression: The time is now {}", dateFormat
.format(new Date()));
}
6. @EnableAsync 和 @Async 使定时任务并行执行
@Component
@EnableAsync
public class AsyncScheduledTasks {
private static final Logger log
= LoggerFactory
.getLogger(AsyncScheduledTasks
.class);
private static final SimpleDateFormat dateFormat
= new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedDelay
= 2000)
public void reportCurrentTimeWithFixedDelay() {
try {
TimeUnit
.SECONDS
.sleep(3);
log
.info("Fixed Delay Task : The time is now {}", dateFormat
.format(new Date()));
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}
}