Use Timer and Timertask in Java

zhaozj2021-02-12  123

Sometimes we need to perform a task every other time, providing Timer and Timertask in Java to complete this task, this article provides an application source code tells you how to use these two classes.

Timer and Timertask have little way, which is also very convenient to use. I hope that if you encounter a problem reference API DOC, it is clear. Timertask is an abstract class that expands Object and implements the runnable interface, so you must implement the public void run () method in your own Task. This is the specific task we need to do. Timer is actually used to control Task, and the main method of him is to overload the Schedule () method. We will use the Schedule (Timertask TASK, Long Time, long "method to explain how to use it.

The source code for the application directly provides the application of the application, and there is too much time to say that it is not very big for beginners. But when you look at them, it is easy to accept. Below I want to complete the task of reading and printing the content from a file every 3 seconds, the contents of the file are as follows: Ming.txtHello WorldBeijing Basketball Javac / C involves some IO knowledge, but not complex. We use bufferedread to read content from the file, read the line, the code is as follows: try {buffredreader br = new bufferedreader (New FileReader ("ming.txt"); string data = null; while ((Data = Br). Readline ())! = null) {system.out.println (data);}} catch ("can not find the file");} catch (ooexception e) {e. PRINTSTACKTRACE ();} In the main program we launched Timer to let him start writing a file. 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 ", int interface) {time.schedule (task, delay * 1000, internal * 1000);}}} The output result is : Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp.

C: /> Java TimeruseHello WorldBeijingBasketballjavac / C Hello WorldBeijingBasketballjavac / C Hello WorldBeijingBasketballjavac / C Hello WorldBeijingBasketballjavac / C

转载请注明原文地址:https://www.9cbs.com/read-7517.html

New Post(0)