Java timer and java Timer

Source: Internet
Author: User

Java timer and java Timer

I have been practicing in Beijing for more than a month, and I have been in touch with a lot of things. Today, the leaders hold a meeting, saying that the server is under too much pressure, the customers are not satisfied, and the access speed is demanding, some operations in our project do not need to be written dynamically to static ones. The content in the static html page is updated regularly on a daily basis (because the customer regularly updates some content on a daily basis, and only updated once ).

I can hear you well. The first time I heard about regular java operations! Things are terrible. I took time out at night and learned the java timer, that is, some basic operations.

Java timers mainly use two classes: Timer (scheduled task scheduling class) and TimerTask (specific task class)

Let's first introduce the TimerTask class. Here we don't directly use this class. This class is an abstract class. We need to set the specific content of our own scheduled task, we can customize a MyTimerTask (the name can be customized) class, but we must inherit the TimerTask class. After inheritance, a run method will be reloaded by default, this method is exactly our detailed task planning method. We can directly write the operations we want to do in this method. This is the most direct method, if you want to do a lot of tasks, you can also write other methods or classes. We can call them in this run method.

Then there is the Timer class. Haha, use it directly. For the usage of this class, refer to the code I gave below! Here I will introduce some basic information about this class:

Timer class constructor:

It seems that there is only one, Timer () // The constructor does not need to explain much, And the instantiation uses

Common Methods:

Method Summary
  cancel()
Terminate this timer and discard all tasks that are currently scheduled.

purge()
Remove all canceled tasks from the task queue of this timer.

schedule(TimerTask task,Date time)
Schedule the task to be executed at the specified time.

schedule(TimerTask task,Date firstTime, long period)
Schedule the specified task to repeat at the specified timeFixed latency execution.

schedule(TimerTask task, long delay)
Schedule the task to be executed after the specified delay.

schedule(TimerTask task, long delay, long period)
Schedule the specified task to start repeating after the specified DelayFixed latency execution.

scheduleAtFixedRate(TimerTask task,Date firstTime, long period)
Schedule the specified task to repeat at the specified timeFixed Rate execution.

scheduleAtFixedRate(TimerTask task, long delay, long period)

Schedule the specified task to start repeating after the specified DelayFixed Rate execution.

Here, I will briefly introduce how to trigger and use the Timer:

Use, look at the following code, combined with the above, it should be clear! The younger brother is not talented. I hope to correct the error if I find it!

public class MyTimerTask extends TimerTask {private static int i = 0;@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println("--------------" + (i++) + "---------------");}}

public class Mytimer {public static void main(String args[]) throws ParseException {Timer time = new Timer();SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date = format.parse("2014-08-19 21:56:03");time.scheduleAtFixedRate(new MyTimerTask(), date, 1000);}}
A certain degree of java basics can be seen, I trigger this scheduled task in a simple java class!

So how can we trigger this opportunity task when our java web project is started? The scheduled task exists as long as the server is enabled. How can we do this, here I will introduce how to use servlet to trigger:

The first thing we need to do is to rewrite the above Mytimer class into a regular servlet class, as shown below:

public class Mytimer extends HttpServlet {public void init() {Timer time = new Timer();SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date;try {date = format.parse("2014-08-19 23:00:03");time.scheduleAtFixedRate(new MyTimerTask(), 0, 1000);} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
Then we need to configure the project's configuration file WEB. XML, where we load the timer when the server is enabled. The detailed configuration is as follows:

<servlet>     <servlet-name>Timer</servlet-name>     <servlet-class>action.TimerUtils.Mytimer</servlet-class>     <load-on-startup>0</load-on-startup>     </servlet>
Let's briefly introduce the functions of load-on-startup! This is also summarized by the netizens I have seen. I didn't know it before!

The value of load-on-startup is generally positive or 0. We usually take 0, 1, 2, 3, 4, and 5. The smaller the value, the higher the load priority.

Okay. Wait a few days for the project to regularly update static html content. Let's see what else needs to be supplemented. It's very late! Say good night to yourself. Come on!







The usage of the timer in java. Here is an example.

Class Working extends TimerTask {
Public void run (){
System. out. println ("I am working ");
}
}

Timer timer = new Timer (false );
Timer. schedule (new Working (), new Date (System. currentTimeMillis () + 2000 ));

Java timer problem, used in a new thread

 
 
 
I believe you mean why runnable only executes once instead of cyclically.

Take a look at the timerExec method documentation:
Public void timerExec (int milliseconds, Runnable runnable)
Causes the run () method of the runnable to be invoked by the user-interface thread after the specified number of milliseconds have elapsed.

It is not said that runnable is periodically executed.

The most direct method for periodic execution is to call timerExec at the end of your runnable run method. For example:

Import org. eclipse. swt. widgets .*;

Class C {
Public static void main (String [] args ){
Final Display display = new Display ();
Final Shell shell = new Shell (display );

Final int duration = 1000;
Display. timerExec (cycle, new Runnable (){
Public void run (){
Shell. setText ("" + new java. util. Date ());
Display. timerExec (cycle, this );
}
});

Shell. open ();
While (! Shell. isDisposed ())
& Nb ...... remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.