Spring定时器_配置文件方式
最近项目中需要定时推送通知到Apple设备中,于是学习了一下Spring定时器的应用,这里分享一下:
Spring定时器是基于quartz实现,我采用的是quartz-all-1.6.0.jar
启用定时器可以在xml配置文件中设置,也可以在代码中定义:
(1)配置文件方式
在Spring的配置文件中分别定义定时任务类,触发器,调度器
<bean name="pushNotificationJob" value-ref="appleDeviceService" /><!--推送通知服务 用于获取待推送的消息 及推送成功后更新消息状态 --><entry key="pushNotificationService" value-ref="pushNotificationService" /> <!--appleDeviceService及pushNotificationService是其他定义的bean--></map></property></bean>
<bean id="cronTrigger" /></property><property name="cronExpression"><!-- 参数指定每隔1小时运行 --><value>0 0 * * * ?</value></property></bean>
<bean /></list></property></bean>
import javapns.notification.transmission.NotificationProgressListener;import javapns.notification.transmission.NotificationThread;import javapns.notification.transmission.NotificationThreads;import org.quartz.JobDataMap;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.springframework.scheduling.quartz.QuartzJobBean;public class PushNotificationTask extends QuartzJobBean {IBaseService appleDeviceService;// 设备serviceIBaseService pushNotificationService;// 推送通知Service/** * 定时推送 */@Overrideprotected void executeInternal(JobExecutionContext context)throws JobExecutionException {JobDataMap dataMap = context.getJobDetail().getJobDataMap();// 这里可以获取配置<entry key>中的各项参数appleDeviceService = (IBaseService) dataMap.get("appleDeviceService");pushNotificationService = (IBaseService) dataMap.get("pushNotificationService"); //任务具体要干什么事,就写在这里了……………… }}