2016/11/24——Spring定时任务
1.Spring3.0以后自主开发的定时任务工具:Spring Task
理解:Spring Task:可以理解为轻量级的Quartz,使用起来非常简单,除了Spring的相关包外不需要额外引包。并且支持配置文件和注解两种方式,推荐使用注解方式。
步骤:
(1)添加Spring Task的相关配置,这里配置在了springmvc.xml中
1 <!-- 开启这个配置,spring才能识别@Scheduled注解 --> 2 <task:annotation-driven /> 3 4 <!-- 自动扫描的包名 --> 5 <context:component-scan base-package="com.spring.task" />
(2)编写定时任务
1 @Component 2 public class MyTaskAnnotation { 3 4 @Scheduled(cron = "0 0 1 * * *") 5 public static void timeTask(){ 6 System.out.println("定时任务1,每天定时几点执行任务"); 7 } 8 9 @Scheduled(fixedRate = 1000*2) 10 public static void timeTask2(){ 11 System.out.println("定时任务2,每隔多少时间执行任务"); 12 } 13 14 }
(3)测试 加载配置文件即可
1 public class TestTimeWork { 2 public static void main(String[] args) { 3 ApplicationContext ctx = new ClassPathXmlApplicationContext("/spring/springmvc.xml"); 4 } 5 }
2.补充
(1)cron属性:
适用于每天几点定时执行一次这种情况,网上很多解释,也有这样工具可以使用
http://www.pdtools.net/tools/becron.jsp

浙公网安备 33010602011771号