JDK中的Timer和TimerTask

来源:互联网 发布:毛孔粗大如何改善知乎 编辑:程序博客网 时间:2024/06/06 18:35

点击打开链接

 Timer是jdk中提供的一个定时器工具,使用的时候会在主线程之外起一个单独的线程执行指定的计划任务,可以指定执行一次或者反复执行多次。

 TimerTask是一个实现了Runnable接口的抽象类,代表一个可以被Timer执行的任务。


一个Timer调度的例子

复制代码
 1 import java.util.Timer; 2 import java.util.TimerTask; 3  4 public class TestTimer { 5      6     public static void main(String args[]){ 7         System.out.println("About to schedule task."); 8         new Reminder(3); 9         System.out.println("Task scheduled.");10     }11     12     public static class Reminder{13         Timer timer;14         15         public Reminder(int sec){16             timer = new Timer();17             timer.schedule(new TimerTask(){18                 public void run(){19                     System.out.println("Time's up!");20                     timer.cancel();21                 }22             }, sec*1000);23         }24     } 25 }
复制代码

运行之后,在console会首先看到:

About to schedule task.
Task scheduled.

然后3秒钟后,看到

Time's up!

__________________________________________________________________________________________________________________

另一个栗子

List<Map<String, Object>> merList = tranService.transExQuery(params);Timer timer = new Timer();OrgMerchantMsgTimerTask task = new OrgMerchantMsgTimerTask(timer, merList);// 延迟0毫秒开始任务,间隔100毫秒重发一次timer.schedule(task, 0, 100);/** * 定时发送消息任务 *  * @author lijinyang */private class OrgMerchantMsgTimerTask extends TimerTask {private Timer timer;private String url = "http://127.0.0.1:****/olt/skcb/callBackNotice?merchOrderId=";private List<Map<String, Object>> merList;public OrgMerchantMsgTimerTask(Timer timer,List<Map<String, Object>> merList) {this.timer = timer;this.merList = merList;}@Overridepublic void run() {if (merList.isEmpty()) {timer.cancel();} else {Map<String, Object> aTran = merList.get(0);String noticeUrl = url + aTran.get("trans_no");try {log.error("----向下游推送异步消息, {}-----", noticeUrl);HttpUtils.httpGetMethod(noticeUrl, "utf-8");} catch (Exception e) {log.error("----向下游推送异步消息失败, {}-----", noticeUrl);}merList.remove(aTran);}}}

import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.params.HttpMethodParams;import org.apache.commons.httpclient.HttpClient;public static String httpGetMethod(String url, String charset) throws Exception {HttpClient client = new HttpClient();client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);GetMethod getMethod = null;try {getMethod = new GetMethod(url);System.out.println("---开始向--"+url+"推送结果-----");int statusCode = client.executeMethod(getMethod);if (statusCode != HttpStatus.SC_OK) {String msg = "访问失败!!HTTP_STATUS=" + statusCode;System.out.println(msg);System.out.println("---向"+url+"推送消息失败---");return null;}// ifString context = getMethod.getResponseBodyAsString();return context;} finally {if (getMethod != null)getMethod.releaseConnection();}// finally}// method


原创粉丝点击