In projects, we often encounter such a requirement that
Program Run at a fixed time, such as scheduled backup. This can be easily done in Java j2se APIs.
Let's inherit the timertask class in Java. util. timertask and put the method to be executed into the run method:
1 Import Java. util. timertask;
2
3 Public Class Mytimertask Extends Timertask {
4
5 @ Override
6 Public Void Run (){
7 System. Out. println ( " The backup program is running ...... " );
8 }
9
10 }
11
Then we use the java. util. Timer class to execute this method. Test class: 1 Import Java. util. timer;
2
3 Public Class Test {
4
5 Public Static Void Main (string [] ARGs ){
6 Timer = New Timer ();
7 Timer. Schedule ( New Mytimertask (), 1000 );
8
9 }
10
11 }
12
We can see the console output:The backup program is running ......
So we want this program to run every five seconds. We can do this:1 Timer. Schedule (NewMytimertask (),0,5000);
The second parameter we passed in is the first execution time of the method, and the third parameter is the execution interval of the method. We can see in the console:The backup program is running ......
The backup program is running ......
The backup program is running ......
The backup program is running ......
Of course, we can also use date for scheduled operations: 1 Timer = New Timer ();
2 Date = New Date ( 107 , 05 , 21 , 00 , 01 , 10 );
3 Timer. Schedule ( New Mytimertask (), date, 5000 );