Sometimes we need to execute a task at intervals and provide timer and timertask in Java to complete this task. This article provides the source code of an application to show 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.
The source code of the application is provided directly below. If you have to say too much, 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
C/C ++