Timer and timertask

Source: Internet
Author: User

Today, I checked the usage of timer and timertask and found some related examples on the Internet,

After the thread starts, it regularly calls the run () method to execute specific task operations. You can reload the timertask class method run () to customize the operations you want.

Example 1:

// Simply print the task parameters.

Public class mytask

Extends java. util. timertask {

String jobname;

Private int I;

Public void run () {// run in interface runnable

System. Out. println (jobname );

}

Public mytask (string jobname ){

This. jobname = jobname;

}

}

// Dotask. Java

Import java. util .*;

Import java. Io .*;

Public class dotask {

Private java. util. Timer timer;

Private java. util. timertask task;

Public dotask (Java. util. timertask task ){

This. Timer = new timer ();

This. Task = task;

}

Public void start (INT delay, int internal ){

Timer. Schedule (task, delay * 1000, internal * 1000); // use the timer. Schedule Method

}

Public static void main (string [] ARGs ){

Java. util. timertask task1 = new mytask ("Job 1 ");

Java. util. timertask task2 = new mytask ("job 2 ");

Dotask Pt = new dotask (task1 );

PT. Start (1, 3 );

Dotask pt2 = new dotask (task2 );

Pt2.start (1, 1 );

}

}

This is to execute repeated tasks at a certain interval. java. util. timer can be easily implemented for you. You can also use multiple threads. The following uses Java. util. timer to implement this function.

Example 2:

// File timeruse

Package SRC;

Import java. util .*;

Import java. Io .*;

Public class timeruse

{

Public static void main (string [] ARGs)

{

Picktask Pt = new picktask ();

PT. Start (1, 3 );

}

}

// File picktask

Package SRC;

Import java. Io. bufferedreader;

Import java. Io. filenotfoundexception;

Import java. Io. filereader;

Import java. Io. ioexception;

Import java. util. timer;

Import java. util. timertask;

Public class picktask

{

Private timer;

Public picktask (){

Timer = new timer ();

}

Private timertask task = new timertask ()

{

Public void run (){

Try {

Bufferedreader BR = new bufferedreader (New filereader ("ming.txt "));

String data = NULL;

While (Data = Br. Readline ())! = NULL ){

System. Out. println (data );

}

}

Catch (filenotfoundexception e ){

System. Out. println ("can not find the file ");

}

Catch (ioexception e ){

E. printstacktrace ();

}

}

};

Public void start (INT delay, int internal)

{

Timer. Schedule (task, delay * 5000, internal * 1000 );

}

}

(1) method selection.

1. Use advanced thread APIs, including:

1. If you want to call a task repeatedly or perform a job after a certain delay, we recommend that you use a combination of Java. util. timer and Java. util. timertask;

2. If you want to write a GUIProgram, We recommend that you use Java. Swing. timer;

3. Class swingworker is used for background threads.

2. inherit from the java. Lang. Thread class.

3. Implement the runnabl interface.

(2) Method Introduction.

1. Use Java. util. timer and Java. util. timertask.

Timer class constructor:

Timer (); // default

Timer (Boolean isdaemon); // whether it is a daemon thread

Usage:

Use a class (mytask) to inherit timertask, place the task to be executed in the run method of the class, and create a timer object (New thread ):

Timer timer = new timer ();

And draw up the plan:

Timer. Schedule (New mytask (), delayedtimeinmillisecond); // used for execution after a certain delay

Timer. Schedule (New mytask (), time); // used for execution at a given time point. Time is an instance of the date class.

Timer. Schedule (New mytask (), initialdelay, interval) // used for repeated execution

Thread termination method:

Timer. Cancel ();

When only the daemon thread is left

When mytaskd run () is executed, all references to timer are removed.

System. Exit (0); // All threads are terminated.

2. inherit the Thread class and overwrite the run () method

There's nothing to say, but remember start ~

The constructor of thread includes:

Thread (threadname );

Thread (runnableobject, threadname );

3. Implement the runnable interface

The method is to implement a runnable class and pass the instance to the constructor of the thread class to create a new thread. For example:

Public class mytask implements runnable {

Private int index;

Public mytask (INT index) {This. Index = index ;}

Public void run (){

System. Out. prinln ("task" + index + "is running .");

}

Public static void main (string [] ARGs ){

For (INT I = 0; I <100; I ++)

New thread (New mytask (I), String. valueof (I). Start ();

}

}

Sometimes we need to execute a task at intervals and provide timer and timertask in Java to complete this task. This article provides an applicationSource codeShows you how to use these two classes.

There are few timer and timertask methods, which are very convenient to use. If you encounter any problems, please refer to the API doc, which is clearly written. Timertask is an abstract class that extends the object and implements the runnable interface. Therefore, you must implement the public void run () method in your task. This is the specific task we need to execute. Timer is actually used to control tasks. The main method provided by timer is the overloaded schedule () method. Here we will use the schedule (timertask task, long time, long internal) method to illustrate how to use it.

Use timer and timertask in Java

-------------------------

The following provides the application source directly.CodeSometimes I feel too much talk about it, and it does not play a very important role for beginners. However, it is easy to accept the code. The following task is to read the content from a file every three seconds and print it to the console. The content of the file is as follows:

Ming.txt

Hello World

Beijing

Basketball

Java

C/C ++

I/O knowledge is involved, but it is not complicated. We use bufferedreader to read content from the file and read the content in one row. The Code is as follows:

Try

{

Bufferedreader BR = new bufferedreader (New filereader ("ming.txt "));

String data = NULL;

While (Data = Br. Readline ())! = NULL)

{

System. Out. println (data );

}

}

Catch (filenotfoundexception E)

{

System. Out. println ("can not find the file ");

}

Catch (ioexception E)

{

E. printstacktrace ();

}

In the main program, we start timer to start reading files. The content of the entire program is as follows:

Import java. util .*;

Import java. Io .*;

Public class timeruse

{

Public static void main (string [] ARGs)

{

Picktask Pt = new picktask ();

PT. Start (1, 3 );

}

}

Class picktask

{

Private timer;

Public picktask ()

{

Timer = new timer ();

}

Private timertask task = new timertask ()

{

Public void run ()

{

Try

{

Bufferedreader BR = new bufferedreader (New filereader ("ming.txt "));

String data = NULL;

While (Data = Br. Readline ())! = NULL)

{

System. Out. println (data );

}

}

Catch (filenotfoundexception E)

{

System. Out. println ("can not find the file ");

}

Catch (ioexception E)

{

E. printstacktrace ();

}

}

};

Public void start (INT delay, int internal)

{

Timer. Schedule (task, delay * 1000, internal * 1000 );

}

}

The output result of the program is:

Microsoft Windows XP [version 5.1.2600]

(C) Copyright 1985-2001 Microsoft Corp.

C: \> JAVA timeruse

Hello World

Beijing

Basketball

Java

C/C ++

Hello World

Beijing

Basketball

Java

C/C ++

Hello World

Beijing

Basketball

Java

C/C ++

Hello World

Beijing

Basketball

Java

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.