最近项目要写个商品定时下架,定时改变订单状态的功能,感觉定时器真的很方便分享下代码:
首先配置Spring定时器扫描:
Spring-config.xml(定时器扫描 )
<task:annotation-driven/>
<context:annotation-config/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<context:component-scan base-package="com.it.web.timer"/>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
最好创建一个单独的类来处理定时任务(com.it.web.timer)
@Component
public class TaskTimer {
@Autowired
private TaskTimerService taskTimerService;
// //每天凌晨0点30分00秒执行
@Scheduled(cron=”0 30 0 * * ?”)
public void goodsCountTask(){
//删除多余 未支付订单
taskTimerService.deleteOrderInfo();
}
}