首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

定时任务Timer施用

2013-07-04 
定时任务Timer使用定时任务Timer使用:Timer有两种执行任务的模式,最常用的是schedule如果你使用的是JDK 5+

定时任务Timer使用
定时任务Timer使用:
    Timer有两种执行任务的模式,最常用的是schedule
    如果你使用的是JDK 5+,还有一个scheduleAtFixedRate模式可以用,
    在这个模式下,Timer会尽量的让任务在一个固定的频率下运行
java代码:

public class StudyTimer {static class MyTask extends TimerTask{String info = "^_^";@Overridepublic void run() {System.out.println(info);}public String getInfo() {return info;}public void setInfo(String info) {this.info = info;}}public static void main(String[] args){Timer timer = new Timer();MyTask task1 = new MyTask();MyTask task2 = new MyTask();task2.setInfo("myTask-2");Calendar cal = Calendar.getInstance();cal.set(Calendar.YEAR, 2013);cal.set(Calendar.MINUTE, 50);System.out.println("start:"+cal.getTime());timer.schedule(task1, 1000,2000);timer.scheduleAtFixedRate(task2, 2000, 3000);while(true){byte[] info = new byte[1024];try {int length = System.in.read(info);String strInfo = new String(info,0,length,"GBK");if (strInfo.startsWith("Cancel-1")) {task1.cancel();}else if(strInfo.startsWith("Cancel-2")){task2.cancel();}else if(strInfo.startsWith("Cancel-all")){timer.cancel();}} catch (IOException e) {e.printStackTrace();}}}}

热点排行