在SSM项目里面使用quart实现定时任务每10秒插入一条数据,使用xml配置方式实现。
1.创建定时任务类
package com.tencent.tusi.test.quartzTest;
import com.tencent.tusi.business.entity.TSystemUsers;
import com.tencent.tusi.business.service.TSystemUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import static com.tencent.tusi.currency.utils.DateUtil.now;
public class InsertUserAfterTenSecond {
@Autowired
public TSystemUsersService tSystemUsersService;
public void insertRecord(){
TSystemUsers user=new TSystemUsers();
user.setcUserName("汤师爷");
user.setcPassWord("984646");
user.setcAddress("m78");
user.setcPhone("11000");
user.setcSex("女");
user.setcDepartmentId(2);
user.setRegisterTime(now());
int i = tSystemUsersService.insertUser(user);
if(i>0){
System.out.println("===========================插入了一条===========================");
}
}
}
定时任务为插入一条数据,返回insert的操作返回数。
2.在quart配置文件里面配置定时任务
设置为每隔10秒执行一次对应的任务
①配置任务类
<!--测试用例,每隔10秒插入一条数据-->
<bean id="insertUserAfterTenSecond" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<bean class="com.tencent.tusi.test.quartzTest.InsertUserAfterTenSecond"/>
</property>
<property name="targetMethod" value="insertRecord"/>
<!--不并发调度-->
<property name="concurrent" value="false"/>
</bean>
targetObject属性指定定时任务类,内容为任务类的路径。targetMethod属性指定任务类下要执行的具体方法。concurrent属性是是否开启作业并发调度。
②定义定时任务触发时间
<!--定时任务测试,每隔10秒想t_system_users中插入一条数据-->
<bean id="inertUserTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="insertUserAfterTenSecond"/>
<!--定时时间,10秒一次,cron表达式-->
<property name="cronExpression" value="*/10 * * * * ?"/>
</bean>
jobDetail属性获取定时任务类的信息。cronExpression(cron表达式)是定义触发时间,这里是每隔10秒触发一次。
③ 配置调度工厂
<bean id="quartzSchedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<!-- <property name="autoStartup" value="true"/> --><!-- 自动启动 -->
<!-- <property name="startupDelay" value="15" /> -->
<property name="triggers">
<list>
<ref bean="inertUserTrigger"/>
</list>
</property>
<property name="taskExecutor" ref="executor" />
</bean>
使用< ref >标签指定Trigger触发器。
运行项目,可以看到数据库里面已经插入了定时任务的数据,时间间隔为10秒