概念:
Quartz是一个开源的作业调度框架,可以让计划的程序任务一个预定义的日期和时间运行。Quartz可以用来创建简单或复杂的日程安排执行几十,几百,甚至是十万的作业数。
框架架构:
简单实例:
maven引用:
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency>
配置文件部分:
需要注意的是,配置文件的部分并不是必须一成不变的,很多地方都有多种写法
<!-- 配置Job类 --> <bean id="job_1" class="com.wazn.learn.scheduler.Job1" /> <!-- <bean id="jobFactory" class="com.wazn.learn.scheduler.BsQuartzJobFactory"></bean> --> <bean id="job1" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="job_1" /> <property name="targetMethod" value="doJob1" /><!-- 类中要执行的方法名称 --> <property name="concurrent" value="false" /> </bean> <!-- 调度触发器 --> <bean id="cronTrigger1" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="job1" /> <property name="cronExpression" value="0/5 * * * * ?" /> </bean> <!-- 调度工厂 --> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <!-- <property name="jobFactory" ref="jobFactory"></property> --> <property name="triggers"> <list> <!-- 触发器列表 有多少配多少--> <!-- <ref bean="cronTrigger1" /> --> </list> </property> </bean>
java定时任务类:
package com.wazn.learn.scheduler; import java.util.Date; public class Job1{ public void doJob1(){ System.out.println("定时任务开始执行:"+new Date().toLocaleString()); } }
接下来是重头戏,调用service:在调用service的过程中,因为没有在实现的方法上加事务的注解,所以每到调用方法的时候就会报错,后来加了事务就可以正常的调用方法了:
调用service的定时任务类:
package com.wazn.learn.scheduler; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import com.wazn.learn.service.teachclass.ClassService; import com.wazn.learn.service.teachclass.ClassTestService; import com.wazn.learn.service.teachclass.homework.HomeWorkService; public class Job1{ @Autowired private ClassTestService testservice; @Autowired private HomeWorkService homeservice; @Autowired ClassService classservice; public void doJob1(){ System.err.println("定时任务开始执行:"+new Date().toLocaleString()); //testservice.updateStatus(); //homeservice.updateStatus(); classservice.updataStatusForEndtime(); } }
方法的实现:
@Override @Transactional public int updataStatusForEndtime() { try { String hql ="update TeachClass set state = false where enddate<=now()"; int i=classdao.execute(hql, null,null); return i; }catch(Exception e) { return 0; } }