使用@scheduled注解实现定时任务
由于使用的是ssm框架 这里无需添加更多的jar包
只需要在spring配置文件中添加
xmlns:task="http://www.springframework.org/schema/task"
然后在xsi:schemaLocation中添加
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
添加扫描注解配置(如果已经在扫描范围可以不添加)
<context:component-scan base-package="com.imwoniu.*" />
<!--配置sping定时器开关 -->
<task:annotation-driven />
这样配置就搞定了
接下来只需要在需要定时任务的类上添加@Component注解
在需要定时的方法上添加@Scheduled注解即可
/**
* 定时任务
* @author Administrator
*
*/
@Component
public class Task {
/**
* 项目启动时 执行一次 只执行这一次
*/
@PostConstruct
public void head() {
System.out.println("--------项目首次启动"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
}
/**
* 项目启动时 执行一次 以后每隔2秒执行一次
*/
@Scheduled(fixedRate = 1000*2)
public void aa() {
System.out.println("-------2秒执行一次---------"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
}
/**
* 项目启动后 每隔10秒执行一次
*/
@Scheduled(cron = "*/10 * * * * *")
public void bb() {
System.out.println("-------每隔10秒执行一次---------"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
}
}
搞定!
还没有评论,来说两句吧...