1、 首先在导入 Spring 所有包的前提下还要导入一个定时器包: quartz-1.6.2.jar ,然后在写一个要执行的任务类,如下:
public class Prison {
public Prison() {}
public void execute() {
List<Into_Prison> prisonlist = new ArrayList<Into_Prison>();
prisonlist=into_prisonService.getAll();
if(prisonlist.size()!=0 ){
for(Into_Prison prison : prisonlist){
if(Integer.parseInt(prison.getIp_Leftday())>0){
prison.setIp_Leftday(String.valueOf(Integer.parseInt(prison.getIp_Leftday())-1));
into_prisonService.save(prison);
}else{
prison.setIp_Leftday("0");
into_prisonService.save(prison);
}
}
}
//System.out.println("======= 执行了吗 ============");
}
private Into_PrisonService into_prisonService;
public Into_PrisonService getInto_prisonService() {
return into_prisonService;
}
public void setInto_prisonService(Into_PrisonService into_prisonService) {
this.into_prisonService = into_prisonService;
}
}
2、 然后在 Spring 中的配置文件如下:
< bean id = "prison" class = "com.prison.action.Prison" >
< property name = "into_prisonService" ref = "into_prisonService" />
</ bean >
以上配置为给任务类的注入
< bean id = "saveProjectJob" class = "org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" >
< property name = "targetObject" >
< ref local = "prison" />
</ property >
< property name = "targetMethod" >
< value > execute </ value >
</ property >
</ bean >
指定任务类中执行的方法: execute ,把任务类的注入给 Spring.
< bean id = "timeTrigger" class = "org.springframework.scheduling.quartz.CronTriggerBean" >
< property name = "jobDetail" >
< ref local = "saveProjectJob" />
</ property >
< property name = "cronExpression" >
< value > 59 59 23 * * ? </ value >
</ property >
</ bean >
设置定时器的时间, 59 59 23 * * ? 为在每天的 23 : 59 : 59 执行
< bean id = "scheduler" class = "org.springframework.scheduling.quartz.SchedulerFactoryBean" >
< property name = "triggers" >
< list >
< ref bean = "timeTrigger" />
</ list >
</ property >
</ bean >
执行定时器
以上定时器主要完成的是把数据库里某个字段的数据过一天就减少一天。
需要注意的是 :
1 、在 <Beans> 中不能够设置 default-lazy-init="true", 否则定时任务不触发,如果不明 确指明 default-lazy-init 的值,默认是 false 。
2、在 <Beans> 中不能够设置 default-autowire="byName" 的属性,否则后台会报 org.springframework.beans.factory.BeanCreationException 错误,这样就 不能通过 Bean 名称自动注入,必须通过明确引用注入。