Write a timer in java to execute a method regularly
Step 1: Write a test class, which extends TimerTask, and re-run() method. The run method contains the logic code you want to execute. The example is as follows:
import java .text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
public class MyTest1 extends TimerTask {
private SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") ;
@Override
public void run() {
System.out.println("The current time is: "+sf.format(new Date()));
//Write program logic code here
}
}
Step 2: Write a class that implements the ServletContextListener interface
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class TimerTaskManager implements ServletContextListener {
private Timer timer;
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("Program regularly executes tasks............................. ........");
MyTest1 t=new MyTest1();
timer=new Timer("Start executing task",true);//
timer.schedule(t, 0, 1000);/ /Execute the run method in MyTest1, t represents a subclass of TimerTask, 0 represents a delay of 0 milliseconds to execute the run method, 1000 represents executing the run method every second, the last two parameters can be defined according to your own needs
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("The scheduled execution task of the program ends...................... ............");
timer.cancel();
}
}
Step 3: Add the following code in web.xml and fill in the path of TimerTaskManager. The program is in the web After the container is started, the contextInitialized method of TimerTaskManager will be initialized and loaded:
Add the listener tag, add the listener-class tag inside the listener, and the content in the listener-class tag is the path of the TimerTaskManager, such as: com.TimerTaskManager
More Write timers in multiple java to execute a method regularly. For related articles, please pay attention to the PHP Chinese website!