最近使用了两种定时任务: 1、Timer 和timer task
Timer是jdk提供的,可以直接继承TimerTask
demo:
每五分钟执行一次,延时0s
class GetBlackipTask extends TimerTask{
@Override
public void run() {
ApiLogger.debug("timer run...");
getBlackIpFromRemote();
}
}
Timer timer=new Timer();
timer.schedule(new GetBlackipTask() , 0, 5*60*1000);
2、quartz 的使用。
quartz和spring集成之后,可以很方便的通过spring的xml配置文件进行配置。
<!--quartz使用 ,配置一个线程池-->
<bean id="executor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="10" />
<property name="maxPoolSize" value="100" />
<property name="queueCapacity" value="500" />
</bean>
<!-- 业务对象 -->
<bean id="reportJob" class="com.push.task.CountReportTask" >
<property name="countService">
<ref local="countService"/>
</property>
</bean>
<!-- 调度业务 -->
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="reportJob" />
<property name="targetMethod" value="report" />
<property name="concurrent" value="false" />
</bean>
<!-- 调度触发器 -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="jobDetail" />
<property name="cronExpression" value="10 0/1 * * * ?" />
</bean>
<!-- 设置调度 -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger" />
</list>
</property>
<property name="taskExecutor" ref="executor" />
</bean>
countReportTask:
/**
* 使用quartz 定时汇报当前的推送量。
* 五分钟推送一次
* @author wdm
*
*/
public class CountReportTask {
private static Logger log = Logger.getLogger("push_count_log");
private CountService countService;
private static String PUSH_COUNT_URL="http://i.open.t.sina.com.cn/subscribe/add_stats.php";
private static int retryTimes = 2;
static HttpClient httpClient;
static{
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
httpClient=new HttpClient(connectionManager) ;
httpClient.getParams().setConnectionManagerTimeout(2000);
HttpConnectionManagerParams params = connectionManager.getParams();
params.setDefaultMaxConnectionsPerHost(100);
params.setConnectionTimeout(2000);
params.setSoTimeout(2000);
}
public void report(){
String pushCountJson=countService.getAllpushCount();
if(DataPush.pushCount.size()!=0){
postCount(pushCountJson);
}else{
log.info("current have't subid to connect..");
}
}
public void postCount(String pushCountJson){
/**业务逻辑 http post**/
}
public CountService getCountService() {
return countService;
}
public void setCountService(CountService countService) {
this.countService = countService;
}
}