在工作中有用到spring task作为定时任务的处理,spring通过接口TaskExecutor和TaskScheduler这两个接口的方式为异步定时任务提供了一种抽象。spring自身也提供了一种定时任务的实现:springtask。spring task支持线程池,可以高效处理许多不同的定时任务。同时,spring还支持使用Java自带的Timer定时器和Quartz定时框架。
TaskExecutor继承Executor,为定时任务的执行提供线程池的支持。
TaskScheduler提供定时任务支持,需要传入一个Runnable的任务做为参数,并指定需要周期执行的时间或者触发器,这样Runnable任务就可以周期性执行了。
java代码:
注解形式:注解@Scheduled(cron="/5 * * * * *")
package com.spring.quartz.quartz;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
/**
* @author cst
* @site www.xiaomage.com
* @company xxx公司
* @create 2019-02-23 16:01
*/
@Service
public class SpringTask {
//spring Task的定时任务
// spring task是单线程的,(当上一个定时任务没有结束的时候,他不会调用新的定时任务)
@Scheduled(cron = "0/5 * * * * *")
public void tast(){
System.out.println("spring task====");
try {
Thread.sleep(10*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("spring task结束-----");
}
}
测试代码:
注解:@EnableScheduling是spring自带定时任务功能,与@Scheduled一起使用
package com.spring.quartz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@SpringBootApplication
public class QuartzApplication {
public static void main(String[] args) {
SpringApplication.run(QuartzApplication.class, args);
}
}