Presentation is loading. Please wait.

Presentation is loading. Please wait.

작업 스케줄링 Lecture #8.

Similar presentations


Presentation on theme: "작업 스케줄링 Lecture #8."— Presentation transcript:

1 작업 스케줄링 Lecture #8

2 강의 목차 J2ME 작업 스케줄링 Timer, TimerTask API Timer, TimerTask 예제 프로그래밍
Mobile Programming

3 J2ME 작업 스케줄링 (1) 특정한 작업을 일정한 시간 동안 지정하여 한 번만 실행하 거나 일정한 간격으로 반복적으로 실행하도록 하는 것 작업 스케줄링 작업 작업을 매일, 매주, 매월 또는 특정 시간(예: 시스템 시동)에 실행하 도록 예약할 수 있다. 작업을 일정한 간격을 두고 반복하여 실행 할 수 있도록 할 수 있 다. 작업 일정을 변경할 수 있다. 예약된 작업을 중지할 수 있다. 예약된 시간에 작업을 실행하는 방법을 사용자가 정의 할 수 있다. Mobile Programming

4 J2ME 작업 스케줄링 (2) 다음의 두 가지 클래스를 이용하여 작업 스케줄링 사용 예: java.util.Timer
특정 작업을 백그라운드 쓰레드에서 스케줄링할 수 있는 기능 제공 java.util.TimerTask Timer를 통해서 스케줄링할 수 있는 특정 작업에 대한 구현 클래스 사용 예: 현재 시간부터 1초 간격으로 특정 작업을 실행 Timer timer = new Timer(true); TimerTask task = new myTimerTask(this); timer.schedule(task, new Date(), 1000); Mobile Programming

5 J2ME 작업 스케줄링 (3) 작업 스케줄링 예제 일정 시간 동안 1초마다 현재 시간을 출력
1 /** 2 * FirstTimerExample.java 3 * 4 * Timer 클래스, TimerTask 클래스 첫번째 예제 5 */ 6 7 // 라이브러리 추가 8 import javax.microedition.midlet.*; 9 import java.util.*; 10 import java.io.*; 11 12 /** 13 * Timer 클래스, TimerTask 클래스 기본 적인 사용 방법 소개 14 */ 15 public class FirstTimerExample extends MIDlet 16 { 17 /** 18 * MIDlet 시작 함수 19 */ 20 protected void startApp() 21 { 22 try FistTimerExample.java Mobile Programming

6 J2ME 작업 스케줄링 (4) FistTimerExample.java 23 { 24 // Timer 생성
23 { // Timer 생성 Timer t = new Timer(); // TimerTask 생성 FirstTimerTask firstTask = new FirstTimerTask("FirstTimerTask"); // 스케줄링 시작, 1초 후 부터 1초 간격으로 스케줄링 t.schedule(firstTask, 1000, 1000); 30 Thread.currentThread().sleep(12000); 32 } 33 catch (Exception e) 34 { e.printStackTrace(); 36 } 37 } 38 39 public void pauseApp() 40 { 41 } 42 43 public void destroyApp(boolean unconditional) 44 { 45 } 46 } 47 48 /** 49 * First TimerTask 50 * 작업 처리 시간을 출력 하는 TimerTask 51 */ FistTimerExample.java Mobile Programming

7 J2ME 작업 스케줄링 (5) FistTimerExample.java
52 class FirstTimerTask extends TimerTask 53 { 54 private String name; 55 56 // 생성자 메소드 57 public FirstTimerTask(String name) 58 { // 현재 작업 이름 설정 this.name = name; 61 } 62 63 // 작업 실행 함수 64 public void run() 65 { // 작업 실행 시간 출력 System.out.println(name + " run at " + getCurrentTime()); 68 } 69 70 // 현재 시스템의 시간을 얻어옴. 71 public String getCurrentTime() 72 { Calendar calendar; calendar = Calendar.getInstance(); return ("" + calendar.get(Calendar.YEAR) + " year " calendar.get(Calendar.MONTH) + " month " calendar.get(Calendar.DAY_OF_MONTH) + " day " calendar.get(Calendar.HOUR) + " hour " calendar.get(Calendar.MINUTE) + " minute " calendar.get(Calendar.SECOND) + " second "); 81 } 82 } FistTimerExample.java Mobile Programming

8 J2ME 작업 스케줄링 (6) * 키 포인트: 24~29 : Timer, TimerTask 생성 및 스케줄링
25 Timer t = new Timer(); 26 // TimerTask 생성 27 FirstTimerTask firstTask = new FirstTimerTask("FirstTimerTask"); 28 // 스케줄링 시작, 1초 후 부터 1초 간격으로 스케줄링 29 t.schedule(firstTask, 1000, 1000); Mobile Programming

9 작업 스케줄링 고려 사항 (1) 작업 스케줄링 실행 방식 Timer의 Exception 처리
여러 개의 TimerTask 중에 한 TimerTask가 긴 시간 동안 Timer를 점유한다면 다른 작업들은 어떻게 되는지에 대한 작업 스케줄링 실행 방식을 고려 Timer의 Exception 처리 여러 개의 TimerTask중 한 TimerTask에서 Exception이 발생하였을 경우 다른 TimerTask에 어떤 영향이 있는지에 대한 Timer의 Exception 처리를 고려 Mobile Programming

10 작업 스케줄링 고려 사항 (2) 작업 스케줄링 실행 방식 고려 사항
Timer가 서로 다른 시작 시간과 반복 시간을 가진 여러 개의 TimerTask를 처리해야 하는 경우 하나의 TimerTask가 긴 시간 동안 Timer를 점유할 때의 다른 TimerTask들의 작업 스케줄링 Timer 인스턴스는 모든 TimerTask가 공유하는 하나의 스레드를 가진다. 긴 시간 작업하는 TimeTask가 스레드를 독점 작업 스케줄링 실행 방식 종류: fixed-delay 방식 fixed-rate 방식 Mobile Programming

11 작업 스케줄링 고려 사항 (3) 작업 스케줄링 실행 방식 Fixed-delay 스케줄링: Fixed-rate 스케줄링:
한 작업의 실행이 다른 이유로 지연되었을 때에 지연 시간만큼 작업의 실행은 지연된다. 애니메이션과 같이 정해진 시간에 작업을 꼭 수행하지 않아도 되는 응용에 사용 Timer의 scheulde 메소드 사용 t.schedule(firstTask, 1000, 1000); Fixed-rate 스케줄링: 한 작업의 실행이 다른 이유로 지연되었을 때에 지연 시간만큼 하지 못한 작업을 수행되도록 스케줄링 주어진 시간 동안 정해진 일을 수행하여야 하는 응용에 사용 Timer의 scheuldeAtFixedRate 메소드 사용 t.scheduleAtFixedrate(firstTask, 1000, 1000); Mobile Programming

12 작업 스케줄링 고려 사항 (4) 작업 스케줄링 실행 방식 예: import javax.microedition.midlet.*;
import java.util.*; import java.io.*; public class LongTimerTaskExample extends MIDlet { protected void startApp() try Timer t = new Timer(); FirstTimerTask firstTask = new FirstTimerTask("FirstTimerTask"); t.schedule(firstTask , 1000, 1000); // t.scheduleAtFixedRate(firstTask , 1000, 1000); LongTimeTimerTask longTask = new LongTimeTimerTask("LongTimeTimerTask"); t.schedule(longTask, 3000); Thread.currentThread().sleep(12000); } catch (Exception e) e.printStackTrace(); Mobile Programming

13 작업 스케줄링 고려 사항 (5) public void pauseApp() { }
{ } public void destroyApp(boolean unconditional) } class FirstTimerTask extends TimerTask { private String name; public FirstTimerTask(String name) // 현재 작업 이름 설정 this.name = name; public void run() System.out.println(name + " run at " + getCurrentTime()); public String getCurrentTime() Calendar calendar; calendar = Calendar.getInstance(); return ("" + calendar.get(Calendar.YEAR) + " year “ Mobile Programming

14 작업 스케줄링 고려 사항 (6) + calendar.get(Calendar.MONTH) + " month "
+ calendar.get(Calendar.DAY_OF_MONTH) + " day " + calendar.get(Calendar.HOUR) + " hour " + calendar.get(Calendar.MINUTE) + " minute " + calendar.get(Calendar.SECOND) + " second "); } class LongTimeTimerTask extends TimerTask { private String name; public LongTimeTimerTask(String name) this.name = name; public void run() try // 6초 동안 sleep 한다. Thread.currentThread().sleep(6000); System.out.println(name + " run at " + getCurrentTime()); catch (InterruptedException ie) { } Mobile Programming

15 작업 스케줄링 고려 사항 (7) public String getCurrentTime() { Calendar calendar;
calendar = Calendar.getInstance(); return ("" + calendar.get(Calendar.YEAR) + " year " + calendar.get(Calendar.MONTH) + " month " + calendar.get(Calendar.DAY_OF_MONTH) + " day " + calendar.get(Calendar.HOUR) + " hour " + calendar.get(Calendar.MINUTE) + " minute " + calendar.get(Calendar.SECOND) + " second "); } Mobile Programming

16 작업 스케줄링 고려 사항 (8) Timer의 Exception 처리
TimerTask에서 실행하다가 Exception이 발생하고 Exception이 Timer에 전달  Timer 인스턴스가 가지는 쓰레드가 중지  같은 Timer에 의해 스케줄링되는 모든 작업이 중지 해결책: Exception을 TimerTask 내에서 처리 Mobile Programming

17 작업 스케줄링 고려 사항 (9) Timer의 Exception 처리 예: 1 /**
1 /** 2 * ExceptionThrowTask 클래스 3 * Exception를 Timer에게 던지는 TimerTask 클래스 4 */ 5 class ExceptionThrowTask extends TimerTask 6 { 7 public void run() 8 { 9 throw new Error("ExceptionThrowTask"); 10 } 11 } Θ 키 포인트 9 : Timer에 Exception을 던짐 9 throw new Error("ExceptionThrowTask"); Mobile Programming

18 작업 스케줄링 고려 사항 (10) Timer의 Exception 처리 예:
Timer t = new Timer(); // Timer 생성 // FirstTimerTask 생성 FirstTimerTask firstTask = new FirstTimerTask("FirstTimerTask"); // FirstTimerTask 스케줄링 시작, 1초 후 부터 1초 간격으로 스케줄링 t.scheduleAtFixedRate(firstTask , 1000, 1000); // ExceptionThrowTask 생성 ExceptionThrowTask exceptionTask = new ExceptionThrowTask(); // ExceptionThrowTask 스케줄링 시작, 5초 후에 1초 간격으로 스케줄링 t.schedule(exceptionTask, 5000, 1000); Mobile Programming

19 작업 스케줄링 고려 사항 (11) Timer의 Exception 처리 해결책:
import javax.microedition.midlet.*; import java.util.*; import java.io.*; public class ExceptionListenerTimerExample extends MIDlet { protected void startApp() try Timer t = new Timer(); FirstTimerTask firstTask = new FirstTimerTask("FirstTimerTask"); t.scheduleAtFixedRate(firstTask , 1000, 1000); ExceptionThrowTask exceptionTask = new ExceptionThrowTask(new ExceptionLogger()); t.schedule(exceptionTask, 5000, 1000); Thread.currentThread().sleep(12000); } catch (Exception e) e.printStackTrace(); Mobile Programming

20 작업 스케줄링 고려 사항 (12) public void pauseApp() { }
{ } public void destroyApp(boolean unconditional) } class FirstTimerTask extends TimerTask { private String name; public FirstTimerTask(String name) this.name = name; public void run() System.out.println(name + " run at " + getCurrentTime()); public String getCurrentTime() Calendar calendar; calendar = Calendar.getInstance(); return ("" + calendar.get(Calendar.YEAR) + " year " Mobile Programming

21 작업 스케줄링 고려 사항 (13) + calendar.get(Calendar.MONTH) + " month "
+ calendar.get(Calendar.DAY_OF_MONTH) + " day " + calendar.get(Calendar.HOUR) + " hour " + calendar.get(Calendar.MINUTE) + " minute " + calendar.get(Calendar.SECOND) + " second "); } interface ExceptionListener { public void exceptionOccurred(Throwable t); class ExceptionLogger implements ExceptionListener public void exceptionOccurred( Throwable t) System.err.println("Exception on Timer thread!"); t.printStackTrace(); class ExceptionThrowTask extends TimerTask ExceptionListener el; public ExceptionThrowTask(ExceptionListener el) { this.el = el; } Mobile Programming

22 작업 스케줄링 고려 사항 (14) public void run() { try
throw new Error("ExceptionThrowTask"); } catch (Throwable t) cancel(); el.exceptionOccurred(t); Mobile Programming

23 Timer Class (1) Timer 클래스
백그라운드에서 한번 실행 되거나 일정한 간격으로 실행을 반복하는 작업에 대해 스케줄링하는 스레드 Timer의 특정 작업이 오랜 시간 진행 된다면, 다음 작업의 실행을 지연시킨다. 모든 작업이 완벽하게 처리된 후 Timer의 작업 실행 스레드는 종료되고 가비지 컬렉션에서 처리된다. Mobile Programming

24 Timer Class (2) Timer 클래스 메소드
void schedule(TimerTask task, long delay) 지정된 시간(delay) 후에 지정된 작업(task)를 처리 void schedule(TimerTask task, Date time) 지정된 시간(time)에 지정된 작업(task)를 처리 void schedule(TimerTask task, long delay, long period) 지정된 시간(delay)이 지난 후에 지정된 간격(period)으로 반복해서 지정된 작업(task)을 처리 void schedule(TimerTask task, Date firstTime, long period) 지정된 시간(firstTime)부터 지정된 간격(period)으로 반복해서 지정된 작업(task)을 처리 void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) void cancel() 현재 진행되고 있는 작업을 제외하고 Timer를 종료 Mobile Programming

25 TimerTask Class (3) Timer 클래스 Timer 클래스 메소드
public abstract class TimerTask extends Object implements Runnable Timer 클래스 메소드 abstract void run() TimerTask에 의해 수행되어질 작업을 정의 boolean cancel() TimerTask를 취소 long scheduledExecutionTime() 작업의 가장 최근 실제 스케줄링된 실행 시간을 돌려 준다. Mobile Programming

26 TimerTask Class (4) Timer 클래스 메소드 예: void run() {
if (System.currentTimeMillis() - scheduledExecutionTime() >= MAX_TARDINESS) return; // 많은 시간 실행이 되지 않으면 작업 종료 // 작업 실행 : } Mobile Programming

27 예제 프로그램 #1 (1) 하늘에서 별이 쏟아지는 예제
Timer 클래스와 TimerTask 클래스를 이용하여 하늘에서 별이 쏟아지는 효과를 표현 시 작 stars[] >= width 화면정보, 초기화, 타이머 설정 종 료 g.drawLine(x,y,x,y) keyPressed NO YES 0.1초 간격 스케줄링, repaint() Mobile Programming

28 예제 프로그램 #1 (2) /** * Timer 클래스와 TimerTask클래스를 이용해
* 하늘에서 별이 쏫아 지는 효과를 표현한 예제 프로그램 */ import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import java.util.*; public class TimerDemo extends MIDlet { Display display; StarField field = new StarField(); FieldMover mover = new FieldMover(); Timer timer = new Timer(); public TimerDemo() display = Display.getDisplay( this ); } protected void startApp() display.setCurrent( field ); // mover TimerTask를 0.1초후 부터 // 0.1초 간격으로 스케줄링함 timer.schedule( mover, 100, 100 ); Mobile Programming

29 예제 프로그램 #1 (3) protected void destroyApp( boolean unconditional ){}
protected void pauseApp(){} public void exit(){ timer.cancel(); // stop scrolling destroyApp( true ); notifyDestroyed(); } class FieldMover extends TimerTask { public void run(){ field.scroll(); } class StarField extends Canvas { int height; // 화면의 전체 높이 int width; // 화면의 전체 넓이 int[] stars; // 화면의 높이 y에 따른 x 좌표를 나타내는 배열 Random generator = new Random(); // Random 객체 boolean painting = false; // paint 함수 처리가 진행 중인가? public StarField(){ height = getHeight(); width = getWidth(); stars = new int[ height ]; for( int i = 0; i < height; ++i ) { stars[i] = -1; // stars 배열을 -1로 초기화 Mobile Programming

30 예제 프로그램 #1 (4) public void scroll() { if( painting ) return;
for( int i = height-1; i > 0; --i ) { stars[i] = stars[i-1]; } // 제일 윗줄 별의 x좌표를 얻어옴 stars[0] = ( generator.nextInt() % ( 3 * width ) ) / 2; // 별의 x좌표가 넓이 보다 크면 그리지 않음 if( stars[0] >= width ) { stars[0] = -1; // 별을 다시 그림 repaint(); protected void paint( Graphics g ){ // paint 메소드가 진행중이다.!!! painting = true; // 화면 전체를 검정색으로 칠한다. g.setColor( 0, 0, 0 ); g.fillRect( 0, 0, width, height ); // 별을 그리기 위해 Graphics의 색을 흰색으로 g.setColor( 255, 255, 255 ); Mobile Programming

31 예제 프로그램 #1 (5) // 화면의 제일 위에서 부터 아래로 별을 그린다.
for( int y = 0; y < height; ++y ) { // 별의 y 높이의 x 좌표를 구한다. int x = stars[y]; // y 높이에 별이 존재 하지 않으면? if( x == -1 ) continue; // 별을 그린다. g.drawLine( x, y, x, y ); } // paint 메소드가 진행이 완료 되었다.!!! painting = false; protected void keyPressed( int keyCode ) { // 키가 눌리면 프로그램을 종료 exit(); Mobile Programming

32 예제 프로그램 #1 (6) Mobile Programming

33 예제 프로그램 #2 (1) 지정된 시간에 알람이 울리는 예제 시간을 지정하고 지정한 시간이 되면 알람이 작동
알람이 작동한 이후 1초에 한번씩 반복해서 작동 1 /** 2 * MIDP Timer 알람 예제 3 * 시간을 지정하고 지정한 시간이 되면 알람이 작동하고 4 * 알람이 작동한 이후 1초에 한번씩 반복해서 작동하게 한다. 5 */ 6 import java.util.*; 7 import javax.microedition.midlet.*; 8 import javax.microedition.lcdui.*; 9 import java.util.Timer; 10 import java.util.TimerTask; 11 12 public class AlarmTimerExample extends MIDlet implements ItemStateListener, 13 CommandListener 14 { 15 private Display display; // 디스플레이 객체 16 private Form mainForm; // 메인 Form 17 private Command startCommand; // 알람 시작 Command 18 private Command resetCommand; // 현재 시간으로 Reset Command 19 private Command exitCommand; // Midlet 종료 Command 20 private DateField alarmDate; // Alarm할 시간을 설정하는 DataField 21 private int dateIndex; // Form에서의 DataField index 22 private Date currentTime; // 현재 시간 23 private Timer timer; // Timer Mobile Programming

34 예제 프로그램 #2 (2) Mobile Programming
24 private AlarmTimerTask task; // Timer에 의해 관리 되는 작업 25 private boolean is_Alarm = false; // 알람 시간이 유효한가? 26 27 public AlarmTimerExample() 28 { 29 // 디스플레이 객체를 얻어옴 30 display = Display.getDisplay(this); 31 // 메인 Form 객체 생성 32 mainForm = new Form("Set Alarm Time"); 33 // 현재 시간을 얻어옴. 34 currentTime = new Date(); 35 36 // 날짜와 시간을 모두 입력 받을수 있는 DateField를 생성 37 alarmDate = new DateField("", DateField.DATE_TIME); // 현재 시간으로 DataField를 설정 39 alarmDate.setDate(currentTime); 40 41 // Command 정의 42 startCommand = new Command("Alarm Start", Command.SCREEN, 1); 43 resetCommand = new Command("Reset Time", Command.SCREEN, 1); 44 exitCommand = new Command("Exit", Command.EXIT, 1); 45 46 // DataField 등록 47 dateIndex = mainForm.append(alarmDate); // Command 등록 49 mainForm.addCommand(startCommand); 50 mainForm.addCommand(resetCommand); 51 mainForm.addCommand(exitCommand); Mobile Programming

35 예제 프로그램 #2 (3) Mobile Programming 52 // 이벤트 등록
// 이벤트 등록 53 mainForm.setCommandListener(this); 54 mainForm.setItemStateListener(this); 55 } 56 57 public void startApp () 58 { 59 // 초기 화면을 메인 Form으로 설정. 60 display.setCurrent(mainForm); 61 } 62 63 public void pauseApp(){} 64 65 public void destroyApp(boolean unconditional){} 66 67 public void itemStateChanged(Item item) 68 { 69 if (item == alarmDate) 70 { // 사용자가 설정한 시간이 현재시간 이전이면 경고 메세지를 // 이후이면 알람을 설정한다. if (alarmDate.getDate().getTime() < currentTime.getTime()) is_Alarm = false; else is_Alarm = true; } 78 } 79 Mobile Programming

36 예제 프로그램 #2 (4) Mobile Programming
80 public void commandAction(Command c, Displayable s) 81 { 82 if (c == startCommand) 83 { if (is_Alarm == false) { // 설정한 알람 시간이 현재 시간 이전 이면 // 경고 메세지를 출력 한다. Alert alert = new Alert("Unable to set alarm", "Please choose another date and time after current time.", null, null); alert.setTimeout(Alert.FOREVER); alert.setType(AlertType.ERROR); display.setCurrent(alert); } else { // 설정한 알람 시간이 유효하면 // 새로운 Timer와 TimerTask를 생성한다. timer = new Timer(); task = new AlarmTimerTask(); 100 // Timer 초기 지연 시간을 구한다. long amount = alarmDate.getDate().getTime() - currentTime.getTime(); // Timer를 초기 지연 시간 후부터 1초 간격으로 작업을 처리 하게 한다. timer.schedule(task,amount, 1000); 105 mainForm.removeCommand(startCommand); mainForm.removeCommand(resetCommand); mainForm.delete(dateIndex); Mobile Programming

37 예제 프로그램 #2 (5) Mobile Programming
110 mainForm.setTitle("Sleeping for " + amount/ " seconds"); 111 } 112 } 113 else if (c == resetCommand) 114 { 115 // 현재 시간으로 DataField를 Reset 116 alarmDate.setDate(currentTime = new Date()); 117 } 118 else if (c == exitCommand) 119 { 120 // 프로그램을 종료 121 destroyApp(false); 122 notifyDestroyed(); 123 } 124 } 125 126 // TimerTask 구현 private class AlarmTimerTask extends TimerTask 128 { int alarmNum = 0; 130 Alert alert; 131 public final void run() { 134 // 처음 작업을 할때 135 // 알람 시간이 되면 Sound와 함께 Text를 보여 준다. Mobile Programming

38 예제 프로그램 #2 (6) Mobile Programming 136 if(alarmNum <= 0) 137 {
137 { 138 mainForm.setTitle("Timer to wake up !!!"); alert = new Alert("Timer to wake up !!!"); 140 } 141 // 두번 이상 작업 할때. 142 // 알람 시작 시간이 몇초 지났는지 알려 줌. 143 else 144 { alert = new Alert("Hurry Up !!!"); 146 alert.setString("Passed " + alarmNum + " seconds"); 147 } 248 149 alert.setTimeout(500); alert.setType(AlertType.ALARM); AlertType.ERROR.playSound(display); display.setCurrent(alert); 153 154 alarmNum++; 155 } 156 } 157 } Mobile Programming

39 예제 프로그램 #2 (7) Θ 키 포인트 16- 19 : Timer, TimerTask 생성
16 private Form mainForm; // 메인 Form private Command startCommand; // 알람 시작 Command private Command resetCommand; // 현재 시간으로 Reset Command private Command exitCommand; // Midlet 종료 Command : TimerTask 스케줄링 23 private Timer timer; // Timer 24 private AlarmTimerTask task; // Timer에 의해 관리 되는 작업 Mobile Programming

40 예제 프로그램 #2 (8) AlarmTimerExample의 초기 실행 화면 알람이 울릴 날짜를 설정하는 화면
Mobile Programming

41 예제 프로그램 #2 (9) 알람이 울릴 시간을 설정하는 화면 알람을 시작 하려는 화면 Mobile Programming

42 예제 프로그램 #2 (10) 알람 설정 시간이 현재 시간 전인 경우 알람이 설정되어 Timer가 작업 관리를 하는 화면
Mobile Programming

43 예제 프로그램 #2 (11) 알람이 울리는 화면 알람이 울리고 4초가 지난 화면 Mobile Programming


Download ppt "작업 스케줄링 Lecture #8."

Similar presentations


Ads by Google