This is an instance that demonstrates how to perform a timed task using Java, which does not end automatically after this instance starts, and then manually ends the program after running this instance.
Copy Code code as follows:
Package com.hongyuan.test;
Import Java.awt.Desktop;
Import Java.io.BufferedInputStream;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.net.URI;
Import java.net.URISyntaxException;
Import Java.nio.charset.Charset;
Import java.text.ParseException;
Import Java.text.SimpleDateFormat;
Import Java.util.Timer;
Import Java.util.TimerTask;
public class Timertasktest {
public static void Main (string[] args) throws ParseException {
Timer timer=new timer ();
SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
Perform a task (in milliseconds) after a specified time delay
Timer.schedule (New TimerTask () {
@Override
public void Run () {
System.out.println ("Time has elapsed 1 seconds!!!!");
}
}, 1000);
Perform a task after a specified time
Timer.schedule (New TimerTask () {
@Override
public void Run () {
try {
Open your browser
Desktop.getdesktop (). Browse (New URI ("http://www.baidu.com/"));
catch (IOException | URISyntaxException e) {
E.printstacktrace ();
}
}
}, Sdf.parse ("2014-04-20 10:20:00"));
To start a task at a specified frequency after a specified time delay
Timer.schedule (New TimerTask () {
@Override
public void Run () {
Bufferedinputstream In=null;
BufferedReader Inbr=null;
try {
Executing system commands
Process p=runtime.getruntime (). EXEC ("ping www.baidu.com");
Read output
in = new Bufferedinputstream (P.getinputstream ());
INBR = new BufferedReader (new InputStreamReader (in,
Charset.forname ("GBK")); My system character set is GBK
String Linestr=null;
while ((Linestr = Inbr.readline ())!= null) {
Obtain output information from the console after command execution
System.out.println (LINESTR);//Print output information
}
Check to see if the command failed to execute.
if (p.waitfor ()!= 0) {
if (p.exitvalue () = = 1)//p.exitvalue () ==0 indicates normal end, 1: Abnormal end
SYSTEM.ERR.PRINTLN ("Command execution failed!");
}
catch (IOException e) {
E.printstacktrace ();
catch (Interruptedexception e) {
E.printstacktrace ();
} finally{
try {
Inbr.close ();
In.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}
}, 10000, 5000);
}
}