SSISO Community

시소당

Timer 와 TimerTask 를 이용한 주기적인 작업

자바에서는  Timer  와  TimerTask  를  이용한  주기적인  작업이  가능합니다.
예를  들어  1분에  한번씩  특정  디렉토리를  감시한다던지.
매일  밤  12시에  백업을  실시한다던지...
이런  기능이  필요하다면  Timer  와  TimerTask  를  사용해보세요.
아래  예제는  1초에  한번씩  카운트  라벨이  바뀌는  스윙  프로그램입니다.

import  java.util.TimerTask;  
import  javax.swing.*;  
import  java.awt.*;  
import  java.util.Timer;  

public  class  LabelChange  {  

public  static  void  main(String[]  args)  {  
MyFrame  frame  =  new  MyFrame();  

Timer  timer  =  new  Timer();  
//TimerTask,  Delay시간,  동작주기  
timer.schedule(new  LabelChangeTimerTask(frame),  0,  (1  *  1000));  
}  
}  

class  MyFrame  
extends  JFrame  {  

private  JLabel  label  =  null;  

public  MyFrame()  {  
this.getContentPane().setLayout(new  BorderLayout());  
label  =  new  JLabel();  
this.getContentPane().add(label,  BorderLayout.CENTER);  
this.setSize(200,  200);  
this.setVisible(true);  
}  

public  void  setLabelValue(String  msg)  {  
label.setText(msg);  
}  
}  

class  LabelChangeTimerTask  
extends  TimerTask  {  

private  MyFrame  frame  =  null;  
private  static  int  cnt  =  0;  

public  LabelChangeTimerTask(MyFrame  frame)  {  
this.frame  =  frame;  
}  

public  void  run()  {  
cnt++;  
frame.setLabelValue(cnt  +  "");  
}  
}
<출처:ibm.com/developerworks/kr>

1567 view

4.0 stars