Code example of using java timer

1. First of all, the timer must be started as soon as the container starts, so we can choose to write the timer in a listener. As soon as the container starts, the listener starts, and then the timer can work.

The first step is to add your own listener to the web XML; The second step is to write a listener and implement the servletcontextlistener interface; The third step is to write a timer, inherit TimerTask, and write specific business logic in the run () method of replication. Step four, copy it in your own listener

public void contextInitialized(ServletContextEvent arg0){ }

This method calls the schedule method of the timer.

The specific codes are as follows:

web. XML add:

MyTimerTaskListener. java

MyTimerTask. java

In addition, there are things to introduce about the timer. It's another example. Ha ha, it's interesting.

After running, we found that three seconds later, the console printed a lot of text, but although the task was completed, the process was not destroyed, and it was still in red. What is the reason?

Creating a timer is equivalent to starting a new thread. This new thread is not a daemon thread, so it will run all the time

There is a cancel () method in both the time class and the TimerTask class

The TimerTask class is used to clear itself from the task queue (a timer object can execute multiple TimerTask tasks)

Timer class is used to empty all tasks in the task queue

The following is an example to delete all files in a directory of the specified disk regularly:

Note that if in the above test code, the date type time I give is earlier than the current time The task task will be executed immediately

summary

The above is the whole content of this article's code example on the use of Java timer. I hope it will be helpful to you. Welcome to: code examples of four traversal methods of map collection, switch usage code examples in Java, and RSA usage code examples of java encryption and decryption. Please leave a message and point out any questions. Thank you.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>