spring实现定时任务的两种方式
1.在spring-servlet.xml文件中加入task的命名空间:
xmlns:task=“http://www.springframework.org/schema/task”
xsi:schemaLocation=“http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd”
然后使用task配置扫描注解
<task:annotation-driven scheduler="qbScheduler" mode="proxy"/>
<task:scheduler id="qbScheduler" />
此时就可以直接使用@Scheduled(cron = "时间格式串"),应用该注解就可以实现定时的功能
@Scheduled(cron = “0/5 * * * * ?”) //每隔5秒执行一次定时任务
public void consoleInfo(){
System.out.println(“定时任务”);
}
第二种方法为:不使用注解实现定时任务,将定时的功能在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-3.0.xsd”
<description>
定时任务
</description>
//定时注解驱动
<task:annotation-driven />
//进行定时任务的类,将其定义为一个bean
<bean id="spaceStatisticsService" class="com.pojo.system.manager.sigar.impl.SpaceStatisticsServiceImpl"></bean>
//通过task标签,定义定时功能
<task:scheduled-tasks>
<task:scheduled ref="spaceStatisticsService" method="statisticSpace" cron="59 59 23 * * ?" />
</task:scheduled-tasks>
@Service
public class SpaceStatisticsServiceImpl implements SpaceStatisticsService
{
@Override
public void statisticSpace()
{
System.out.println(“实现定时功能”);
}
}
总结:两种方法都能实现定时的功能,但明显第一种方式会比较简洁,而且更加方便。