In development, we often need periodic operations, such as doing an operation every few minutes. We're going to set a timing,
Then go ahead and develop my first Java timer, theJava Timer Utility allows you to execute threads or tasks at a predetermined future time, and can repeat frequencies based on a set of these tasks. Design and implement a timer that uses the Model-control-view (MVC) design pattern.
Begin:
First, construct W to build the simplest Java Web project. Here I use the most myeclipse, the benefits naturally needless to say, who use who know, of course if
You're to use a different IDE or you can.
Creating a new Web application in MyEclipse is simple, click File-new-webproject, and enter our project name.
This time the system will generate a lot of things, we find webroot below the index.jsp page, enter
Hello world! Launch our tomcat, OK this time our first Web project is built;
Now that we have our first Java Web program, we can try to write a Java Web timer.presentation Layer (View)We usually refer to the presentation layer of the Web application as the view presentation layer,. It will include a screen display timer at any time of the state, as well as a set of buttons to control the activation of the timer (Start Timer) and deactivation (Stop Timer). You can also define a timer interval of seconds to repeat a director's task. Finally, aRefresh Screenbutton to display the Update event notification on the screen.
model LayerThere are two main classes in the model layer,
MyTimerand the
Display(Its purpose is to report a status timer that it can display).Let's take a look at their structural system:
Display The class has three methods and constructors. In the constructor
Display() , the
display property is initialized to an empty string. the method
getDisplay() returns the contents
display of a property . Finally, the method
insert(value) takes a string as a parameter, creates a line break and adds it to the
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>"; }
Class MyTimer directly interacts with the JSP page. MyTimeryou can perform various actions, including starting a timer ( timerStarted() ), stopping the timer ( timerStopped() ), and displaying event notifications () on the screen getDisplay() . It consists of two properties: Object display and timer .
when an object myTimer when created, the constructor passes a parameter called What seconds , which is Integer of type (This parameter defines the period of the timer, which is converted to milliseconds.) Timer is a specific class that belongs to the Java utility package and allows a thread to operate the task, which can be started at some time in the future and stopped when needed. Its scheduleAtFixedRate() method is used to schedule the task to repeat the fixed rate of execution. This requires three parameters: Task Execution ( MyTask ), before the delay timer starts (set to 0), and the time is converted to milliseconds. Create and start a timer, create a new objectmyTimer
Public MyTimer (Integer seconds) { timer = new timer (); Long msec = +; display = new display (); Timer.scheduleatfixedrate (New MyTask (), 0*msec, seconds.intvalue () *msec); Display.insert ("Timer is started.");
The task schedule for a timer is defined as
MyTask类 , this class inherits from Timetask and extends the
TimerTask --The Java utility package for another class.
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() method to stop the timer, its implementation is very simple. It invokes the Cancel () method of the timer object and then creates an event notification that is displayed on the screen of the Web application.
public void timerstopped () { timer.cancel (); Display.insert ("Timer has stopped.");
One last method
getSnapshot()
将作为一个字符串返回的结果的方法getDisplay()从对象display中提取getDisplay();。 该方法用于更新web应用程序的屏幕。
Public String Getsnapshot () { snapshot=display.getdisplay (); return snapshot; }
creating interfaces to introduce Jstl
<% @page contenttype= "text/html" pageencoding= "UTF-8"%><%@ taglib uri= "Http://java.sun.com/jsp/jstl/core" Prefix= "C"%>
Since our number of seconds is 1-9, we can use Jstl to loop out a simple drop-down list box for us to choose
<%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> perfecting the view layer </strong></div><div><strong></strong><pre name= "code" class= " HTML ">
Configuration<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>
Control layerHere the control layer, I used two different methods, one is to use the JSP page to introduce JSTL, to judge, jump. Another way is to use servlets to control jumps. In fact, a JSP is a simple servlet, in the JSP page Process Control has a benefit, is not to the Web. XML inside to configure, relatively simple, convenient. I've used both of these ways.
@Overrideprotected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException { try {//Get interval seconds integer second = new Integer (Req.getparameter ("second"));//Get object MyTimer MyTimer = (mytimer) req.getsession ( ). getattribute ("MyTimer");//Determine if the object exists, if it exists, it is repeated click the Start button, here first end, the current thread, and then start new; if (MyTimer! = null) {//stop Timermytimer.timerstopped ();} New object, new method, new Thread MyTimer = 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 ();}}
If we go to the JSP page to control, then first to create a folder, I named control here, and then write the method inside.<% @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"/>
All right, here's a simple Java timer that's done, so let's take a look at the running effect.
The source code has been uploaded, want to see can go to download http://download.csdn.net/detail/liaodehong/9052595
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
My first Java timer