版权声明:本文为博主原创文章,转载请附上原文链接。 https://blog.csdn.net/Jayszxs/article/details/82984135
1. 配置spring-mvc.xml文件
在xmlns中增加:
xmlns:task="http://www.springframework.org/schema/task"
schemaLocation中增加
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
再配置task相关
<!-- 通知spring容器通过注解的方式装配bean -->
<context:annotation-config />
<!-- 通知spring容器采用自动扫描机制查找注解的bean -->
<context:component-scan base-package="com.jz" />
<!-- 定时器开关 -->
<task:annotation-driven />
对应的任务bean
package com.jz.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@Lazy(false)
@EnableScheduling
public class testTask{
@Scheduled(cron = "0/3 * * * * ? ") // 间隔3秒执行
public void taskIndex() {
System.out.println("每三秒执行一次~");
}
}
将tomcat启动,就可以看到效果了。
2. 无法是用注入的问题
因为@Autowired/@Resoure等注入的优先级在@Scheduled之下,所以如果在任务中使用注入启动会报错。
解决办法:只能手动去获取该bean
ApplicationContext application = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
// 将object改成需要的bean
Object obj = application.getBean("xxxxx需要注入的bean");
如果不想使用该方法,则使用Quartz~~~~~