The use of timer in JAVA

 

1-------------------------------------------------------------

 

 

The two classes used to implement the timer function in JAVA are Timer and TimerTask. The
       Timer class is a class used to execute tasks. It accepts a TimerTask as a parameter.
Timer has two modes of executing tasks. The most commonly used is schedule, which can Execute the task in two ways: 1: at a certain time (Data), 2: after a certain fixed time (int delay). Both ways can specify the frequency of task execution. There are two examples in this article, one The simple
one is to use an inner class
1. A simple instance

  first writes a class

public class TimeTest {
public static void main(String[] args) {
    
     Timer timer = new Timer();
     timer.schedule(new MyTask(),1000 ,2000);
}

Then write a class
public class MyTask extends TimerTask{

    @Override
    public void run() {
  System.out.println("Start running");        
    }
}

This can complete a simple timer, but still One way is to write these two classes into one class, which is the inner class

2. Inner class

public class SerchRun {

    protected static void startRun(){
        Timer timer = new Timer();
         TimerTask task = new TimerTask(){
             public void run(){
                 System.out.println("Start running"); //Write what you want to call here Method
             }
         };
      timer.scheduleAtFixedRate(task, new Date(), 2000);//Start at the current time and restart every 2 seconds
     // timer.scheduleAtFixedRate(task, 1000,2000); // Start after 1 second Restart every 2 seconds                 
     }
    
    public static void main(String[] args) {
      SerchRun.startRun();
    }
}

 

The difference between schedule and scheduleAtFixedRate is that if the specified start time is before the current system running time, scheduleAtFixedRate will execute the elapsed time as a cycle, while schedule will not count the elapsed time.

for example:

SimpleDateFormat fTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  Date d1 = fTime.parse("2005/12/30 14:10:00");
  
  t.scheduleAtFixedRate(new TimerTask(){
   public void run()
   {
       System.out.println("this is task you do6");
   }
  },d1,3*60*1000);

The interval time is 3 minutes, and the specified start time is 2005/12/30 14:10:00. If I execute this program at 14:17:00, it will print 3 times immediately

this is task you do6     //14:10
this is task you do6     //14:13
this is task you do6     //14:16

And note that the next execution is at 14:19 instead of 14:20. That is, the timing starts from the specified start time, not from the execution time.

However, if the schedule method is used above, the interval time is 3 minutes, and the specified start time is 2005/12/30 14:10:00, then if the program is executed at 14:17:00, the program will be executed once. And the next execution time is 14:20, not the period (14:19) counted from 14:10.

 

 

 

2-------------------------------------------------------------

 

 

In many cases, we need to use the timer

For example: regularly delete some junk information in the database (that is, things that are not used, but occupy a place)
In CMS, we use timers to regularly publish articles, and regularly delete unused files uploaded...
Timer , as the name suggests, reminds something at a specified time.
From this explanation, it is not difficult to understand that the timer needs to use two things: 1. Timing; 2. Task (executed event)
to solve the following first problem: Timing
In java programming, used for Timing classes include: Timer
In this class, there are many methods, the most commonly used is the schedule method, several of which are overloaded in this class, but the main purpose is to start at a certain point in time and execute regularly For a certain task, this method ensures the realization of the overall function of the timer. The
second problem: task
When we have time, we need to give the machine a task and let it execute the task after a specified time. This task class can inherit TimerTask class to implement, in this case, you can get a new task class, this task class mainly overrides a run() method, in this method we write the specific tasks that need to be executed, this class will be referenced when Execute this method.
Look at the method below:
Task class:
import java.util.*;
public class Task extends TimerTask {
    public void run() {
        System.out.println("I am Task" + "The time is now:" + new Date()) ;
    }
}
Timing class:
import java.util.Timer;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;
public class Dingshiqi {
    public static void main(String[] args) {
        Timer timer = new Timer();            
        Task task = new Task( );
        timer.schedule(task, new Date(), 2000);
    }
}
The effect of this is that every 2 seconds, "I am a Task, the current time is (current time)" is output.

 

Timer, we can use it in servlet, this is more commonly used,
let Write some attribute values ​​in xml file, then get the value in servlet, and then in servlet's init method Call the timing function, and finally, destroy() to destroy
the servlet with some corresponding processing in the timer xml:
<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>Admin_servlet</servlet-name>
    <servlet-class>com.cbh.lmodules_article.servlet.Admin_servlet</servlet-class>
    <init-param>
            <param- name>startTask</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>intervalTime</param-name>
            <param-value>1</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
  </servlet>

The init method in the servlet starts the timer
public void init() throws ServletException {
        ServletContext context = getServletContext();
        // (true is to refresh the cache with a fixed time)
        String startTask =getInitParameter("startTask");
        // Timing refresh time( minutes)
        //Long delay = Long.parseLong(getInitParameter("intervalTime"));
        // start the timer
        if (startTask.equals("true")) {
            timer1 = new Timer(true);
            task1 = new Timer_task(context );
            System.out.println("TimerServlet2 timer has started");           
            timer1.schedule(task1,0, 60*1000);
            System.out.println("TimerServlet2 has added a task schedule");
        }
    }
The destroy method in the servlet destroys the timer
public void destroy() {
        super.destroy();
        if (timer1 != null) {
            timer1.cancel();
            System.out.println("TimerServlet2 timer has been destroyed");
        }
    }
If the timer is used in the servlet, then the association with the task needs to be established. How to establish the association?
public class Timer_task extends TimerTask {
    private ServletContext context;
    private static boolean isRunning = false;
    public Timer_task(ServletContext context){
     this.context = context; //There are parameters to construct to realize the association with servlet
    }
    Admin_service as=new Admin_service();
    @Override
    public void run() {
        as.delte("");
    }

}

 

 

 

 

 

3-------------------------------------------------------------

 

 

java.util.Timer
A threading facility that schedules tasks for later execution in a background thread. Tasks can be scheduled to run once, or to repeat at regular intervals. This class is thread-safe: multiple threads can share a single Timer object without external synchronization.
java.util.TimerTask
A task scheduled by a Timer to execute once or repeatedly.
How to complete the timing operation function through these two classes? The specific method of use is described below through a specific demo .
This demo implements such a function. During the running of the system, every 30 minutes, the system automatically checks the number of available connections in the connection pool and outputs it to the log.
First create a task class that needs to be executed regularly. This task class needs to inherit TimerTask , and then rewrite the run() method . The code in the run() method body is the operation that needs to be executed periodically. In this demo , it is to obtain the connection pool. The current number of available connections is output to the log. The specific implementation code is as follows:

publicclass TaskAvailableConnectNumber extends TimerTask {

 

   private Logger log = Logger.getLogger(TaskAvailableConnectNumber.class); 

   private ConnectionPool pool=ConnectionPool.getInstance();  

   @Override

   publicvoid run() {

   log .debug( " Number of available connections in the current connection pool " + pool .getAvailableConnectNumber());

   }

}

 

A listener is defined below, which is responsible for turning on the timer when the application server starts. The listener needs to implement the ServletContextListener interface and rewrite the contextInitialized() and contextDestroyed() methods. The code is as follows:

publicclass OnLineListener implements ServletContextListener{

  

   private Logger log = Logger.getLogger(OnLineListener.class);

   Hours timer = zero ;

   // This method will be executed when the application server starts

   publicvoid contextInitialized(ServletContextEvent arg0) {

     

        // Create a timer to schedule tasks that need to be executed regularly.

      timer = new Timer ();

      // Arrange the task that needs to be executed regularly for the timer. The task is the task class TaskAvailableConnectNumber created earlier , and specifies that the task is executed every 30 minutes.

      timer.schedule(new TaskAvailableConnectNumber(), 0, 30*60*1000);

      log .debug( " Start timer " );

   }

    // When the application server is closed, this method will be executed to complete the operation of closing the timer.

publicvoid contextDestroyed(ServletContextEvent arg0) {

      if(timer!=null){     

         timer .cancel(); // Close the timer

         log .debug( "----- Timer destruction -------" );

      }

   }

}

 

       For the listener to run normally, it needs to be configured in the web.xml file. The configuration information is as follows:

<!-- Listener configuration start -->

   <listener>

      <listener-class>

         cn.sdfi.listen.OnLineListener

      </listener-class>

   </listener>

<!-- Listener configuration end -->

 

After the above steps are completed, a simple timer is even developed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326486581&siteId=291194637