Java timer usage
The timer class timer is in the Java. util package.
In use, the instance is first instantiated, and then the schedule (timertask task, long delay) method of the instance is used to set the specified task to be executed after the specified delay.
The timer task class timertask is an abstract class that inherits and overwrites its run () method to implement specific tasks.
Schedule (timertask task, date time) sets the task to be executed at the specified time.
The schedule (timertask task, long delay, long period) method is used to set the scheduled task to execute a fixed-latency peroid after the specified delay.
The scheduleatfixedrate (timertask task, long delay, long period) method sets a fixed frequency of peroid execution for a specified task after a specified delay of delay.
The cancel () method ends this timer.
To implement a scheduled task, using the timer and timertask classes in Java can easily call processing functions in real time.
These two classes are very convenient to use and can fulfill the vast majority of timer needs.
Package COM. demo. timer; import Java. io. ioexception; import Java. util. timer;/*** Java timer usage **/public class timertest {public static void main (string [] ARGs) {timer = new timer (); // execute this task after 1 second, every 2 seconds. If you pass a data parameter, You can execute this task at a fixed time. timer. schedule (New mytask (), 1000,200 0); // This is used to stop this task, otherwise it will be executed cyclically while (true) {try {int CH = system. in. read (); If (CH-'c' = 0) {system. out. println ("Stop task"); timer. cancel (); // exit the task using this method} catch (ioexception e) {e. printstacktrace () ;}}/ *** assume an internal class */static class mytask extends Java. util. timertask {public static int I = 0; @ overridepublic void run () {I ++; system. out. println ("________" + I );}}}