首先,要创建你自己想要定时的实体类
@Service("smsService")
@Transactional
public class SmsSendUtil {
@Autowired
private SmsDao smsDao;
@Autowired
private ShortLinkService shortLinkService;
private Logger logger = Logger.getLogger(this.getClass());
下面的这个方法要是无参的
public synchronized void taskSendSms() {
Map<String, Object> columnMap = new HashMap<String,Object>();
columnMap.put("status", "0");
List<Sms> smsList = smsDao.selectByMap(columnMap);
for (Sms sms : smsList) {
logger.info("开始发送短信:手机号:"+sms.getPhone()+",短信内容:"+sms.getSendtext());
String result = "";
try {
result = shortLinkService.sengMessage(sms.getPhone(), sms.getSendtext());
} catch (Exception e) {
logger.error("短信发送失败!");
logger.info("失败短信:手机号:"+sms.getPhone()+",短信内容:"+sms.getSendtext());
e.printStackTrace();
}
Sms upSms = new Sms();
upSms.setId(sms.getId());
sms.setSendcount(sms.getSendcount()+1);
sms.setSendtime(new Date());
if ("success".equals(result)) {
sms.setStatus("1");
smsDao.update(sms, upSms);
}else {
sms.setStatus("0");
smsDao.update(sms, upSms);
}
}
}
}
第二步就是在配置文件中配置定时任务
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- 定时任务获取增量数据-->
<bean id="sendFailedReturnDataRecord1" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail">
<bean id="sendFailedReturnDataRecord2" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<bean id="sendFailedReturnDataRecord3" class="ins.platform.common.util.SmsSendUtil"><!-- 类位置 -->
</bean>
</property>
<property name="targetMethod">
<value>taskSendSms</value> <!-- 方法名 -->
</property>
</bean>
</property>
<property name="cronExpression" value="0 30 * * * ? *"></property> <!-- 执行频率,每小时的第一秒触发 -->
</bean>
<!-- 设置调度 -->
<bean id="SpringJobSchedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="sendFailedReturnDataRecord1"/>
</list>
</property>
</bean>
</beans>
最后一步就是要在spring配置文件中将上述配置引入,就会开启定时了