我的第一個java定時器

來源:互聯網
上載者:User

標籤:java   web開發   線程   

在開發中,我們經常需要一些周期性的操作,例如每隔幾分鐘就進行某一項操作。這時候我們就要去設定個定時,

接下來就去開發我的第一個java定時器吧,Java計時器公用程式允許您執行線程或任務在一個預先確定的將來的時間,並根據一組這些任務可以重複頻率。 設計和實現一個計時器,會用到model-control-view(MVC)設計模式。

開始:

首先來構w建一個最簡單的java Web 專案吧。這裡我用的是最myeclipse,好處自然不必多說,誰用誰知道,當然如果

你要用其他IDE也可以。

在myeclipse中建立一個新的web應用程式很簡單,點擊File-new-WebProject,輸入我們的項目名就可以了。

這個時候會系統會產生很多東西,我們找到WebRoot 下面的index.jsp頁面,輸入

Hello World!啟動我 們的tomcat,好了這個時候我們的第一個web項目就構建完成了;
現在我們已經有了自己的第一個 java web 程式了,可以嘗試去寫一個java web 計時器了;展示層(View)我們通常把web應用程式的展示層稱為視圖展現層,。 它將包括一個螢幕顯示計時器在任何時候的狀態,以及一組按鈕控制計時器的啟用(啟動計時器)和失活(停止計時器)。 您還可以定義定時器的間隔秒重複一個導演的任務。 最後,一個重新整理螢幕按鈕將更新事件通知顯示在螢幕上。
模型層模型層主要有兩個類, MyTimerDisplay(其目的是報告的狀態計時器,它可以顯示).先看一看他們的結構體系:
Display類有三個方法和建構函式。 在建構函式中 Display(), display屬性初始化為一個Null 字元串。 該方法 getDisplay()返回屬性的內容 display。 最後,該方法 insert(value)接受一個字串作為參數,建立了一個分行符號,並將其添加到 display;

 public void insert(String value) {        Calendar now = Calendar.getInstance();        String stamp = now.get(Calendar.HOUR_OF_DAY)+":"+now.get(Calendar.MINUTE)+                ":"+now.get(Calendar.SECOND)+" - ";              display+=stamp+value+"\n<br>";    }

MyTimer直接與JSP頁面互動。MyTimer可以執行各種操作,包括啟動一個計時器(timerStarted()),停止計時器(timerStopped()),並在螢幕上顯示事件通知(getDisplay())。 它包含兩個屬性:對象displaytimer

當對象myTimer被建立時,建構函式傳遞一個參數叫什麼seconds,它的類型為Integer(該參數定義了定時器的時期,這是轉換為毫秒。Timer是一個具體的類,屬於Java公用程式包和允許一個線程操作任務,可以在需要時啟動在未來某個時間和停止。 它的scheduleAtFixedRate()方法是用來計劃任務重複固定利率執行。 這需要三個參數:任務執行(MyTask),延遲計時器開始前(設定為0),和時間轉換為毫秒。 建立並啟動一個計時器,就建立一個新的對象myTimer

 public MyTimer(Integer seconds) {        timer = new Timer();        long msec = 1000;        display = new Display();                timer.scheduleAtFixedRate(new MyTask(), 0*msec,                 seconds.intValue()*msec);                display.insert("Timer is started.");    }

計時器的任務時間表是定義為 MyTask類,此類繼承自TimeTask,並擴充了 TimerTask——另一個類的Java公用程式包。 MyT

ask作為MyTimer的一個私人內部類,允許操作對象display。 因此,MyTask作用是為了在一個時間段顯示的去調用執行

display對象的insert方法.

public class MyTimer {    private Timer timer;    private Display display;        private String snapshot;    public MyTimer(Integer timeSecond) {    }    private class MyTask extends TimerTask {        @Override        public void run() {            // task to do            display.insert("New event.");        }

timerStopped()方法停止計時器,它的實現非常簡單。 它調用timer對象的cancel()方法,然後建立一個事件通知,顯示在螢幕上的web應用程式。

 public void timerStopped() {        timer.cancel();        display.insert("Timer has stopped.");    }

最後一個方法 getSnapshot() 將作為一個字串返回的結果的方法getDisplay()從對象display中提取getDisplay();。 該方法用於更新web應用程式的螢幕。

 public String getSnapshot() {        snapshot=display.getDisplay();        return snapshot;    }

建立介面引入JSTL

<%@page contentType="text/html" pageEncoding="UTF-8" %><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
由於,我們的秒數是1-9,所以可以利用JSTL,迴圈出來一個簡易的下拉式列表框,供我們選擇

<%Integer seconds[] = {new Integer(1),new Integer(2),new Integer(3),                    new Integer(4),new Integer(5),new Integer(6),                    new Integer(7),new Integer(8),new Integer(9)};request.setAttribute("seconds", seconds);Integer second=(Integer) session.getAttribute("second");if(second==null) {    session.setAttribute("second", seconds[0]);}%>
</pre><strong></strong><div><strong></strong></div><div><strong>完善視圖層</strong></div><div><strong></strong><pre name="code" class="html"><html>    <head>        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        <title>JSP Page</title>        <style type="text/css">            #foo { overflow-y: hidden; }            .bar { float: left; margin:5px 5px 5px 5px; }            .screen {border:solid 4px;width:500px;height:300px;                     background-color:beige; padding: 5px 5px 5px 5px;                     overflow:scroll}</style>    </head>    <body>        <h1>Hello World!</h1>        <div id="foo">            <div class="bar">                <form method="post" action="start.action">                    間隔 (秒)                    <select name="second">                        <c:forEach items="${seconds}" var="row">                            <c:if test="${row != second}">                                <option>${row}</option>                            </c:if>                            <c:if test="${row == second}">                                <option selected="">${row}</option>                            </c:if>                        </c:forEach>                    </select>                    <input type="submit" value="開始  計時">                </form>            </div>            <div class="bar">                <form method="post" action="stop.action">                    <input type="submit" value="停止  計時">                </form>            </div>            <div class="bar">                <form method="post" action="control/doRefresh.jsp">                    <input type="submit" value="重新整理">                </form>            </div>        </div>        <c:if test="${mytimer == null}">            <div class="screen" style="border-color:red">                ${display}            </div>        </c:if>        <c:if test="${mytimer != null}">            <div class="screen" style="border-color:green">                ${display}            </div>        </c:if>    </body></html>

配置
 <servlet>    <servlet-name>StratServlet</servlet-name>    <servlet-class>servlet.StartServlet</servlet-class>  </servlet> <servlet-mapping>    <servlet-name>StratServlet</servlet-name>    <url-pattern>/start.action</url-pattern>  </servlet-mapping> <servlet>    <servlet-name>StopServlet</servlet-name>    <servlet-class>servlet.StopServlet</servlet-class>  </servlet> <servlet-mapping>    <servlet-name>StopServlet</servlet-name>    <url-pattern>/stop.action</url-pattern>  </servlet-mapping>

控制層

這裡控制層,我用了兩種不同的方法,一種是使用在JSP頁面引入JSTL,進行判斷,跳轉。還有一種是使用Servlet,進行控制跳轉。其實一個JSP也就是一個簡易的Servlet,在JSP頁面進行流程式控制制有一個好處,就是不用到Web.xml裡面去配置,比較簡單,方便。這裡我兩種方式都採用了。

@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {try {//得到間隔秒數Integer second = new Integer(req.getParameter("second"));//得到對象MyTimer mytimer = (MyTimer) req.getSession().getAttribute("mytimer");//判斷對象是否存在,如果存在,就表明重複點擊了開始按鈕,這裡先結束一下,當前的線程,再開始新的;if (mytimer != null) {// stop timermytimer.timerStopped();}//新對象,新方法,新線程mytimer = new MyTimer(second);req.getSession().setAttribute("mytimer", mytimer);req.getSession().setAttribute("display", mytimer.getSnapshot());req.getSession().setAttribute("second", second);resp.sendRedirect("\\index.jsp");} catch (Exception e) {e.printStackTrace();}}

如果我們去JSP頁面去控制的話,那麼首先先去建立一個檔案夾,我這裡取名叫control,接著在裡面寫方法.

<%@page contentType="text/html" pageEncoding="UTF-8" import="data.*" %><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%Integer second= new Integer(request.getParameter("second"));MyTimer mytimer = (MyTimer) session.getAttribute("mytimer");if(mytimer!=null) {    // stop timer    mytimer.timerStopped();}mytimer = new MyTimer(second);session.setAttribute("mytimer", mytimer);session.setAttribute("display", mytimer.getSnapshot());session.setAttribute("second", second);%><c:redirect url="/index.jsp"/>
好了到這裡一個簡易的Java計時器就完成了,接下來看一看運行效果吧;



原始碼已上傳,想看看的可以去下載http://download.csdn.net/detail/liaodehong/9052595

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

我的第一個java定時器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.