java定时任务实例_使用java执行定时任务示例

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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值