Java-based scheduled execution Program

Source: Internet
Author: User
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 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.