您的位置:首页 > 编程语言 > Java开发

java任务计划

2014-04-27 00:56 302 查看
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");

//延迟指定时间后执行任务(以毫秒为单位)
timer.schedule(new TimerTask(){

@Override
public void run() {
System.out.println("时间已经流逝1秒!!!!");
}

}, 1000);

//到达指定时间后执行任务
timer.schedule(new TimerTask(){

@Override
public void run() {
try {
//打开浏览器
Desktop.getDesktop().browse(new URI("http://www.baidu.com/"));
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}

}, sdf.parse("2014-04-20 10:20:00"));

//延迟指定时间后以指定频率开始执行任务
timer.schedule(new TimerTask(){

@Override
public void run() {
BufferedInputStream in=null;
BufferedReader inBr=null;
try {
//执行系统命令
Process p=Runtime.getRuntime().exec("ping www.baidu.com");

//读取输出
in = new BufferedInputStream(p.getInputStream());
inBr = new BufferedReader(new InputStreamReader(in,
Charset.forName("GBK"))); //我的系统字符集为GBK
String lineStr=null;
while ((lineStr = inBr.readLine()) != null){
//获得命令执行后在控制台的输出信息
System.out.println(lineStr);// 打印输出信息
}

//检查命令是否执行失败。
if (p.waitFor() != 0) {
if (p.exitValue() == 1)//p.exitValue()==0表示正常结束,1:非正常结束
System.err.println("命令执行失败!");
}

} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
try {
inBr.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}, 10000, 5000);

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: