dev/java 배포
java batch scheduler #010
strange-dev
2025. 5. 6. 22:10
반응형
java 배치 스케줄러
- #005 작성된 소스에 추가합니다.
2025.04.29 - [dev/java 배포] - java properties 조회 #005
java properties 조회 #005
db 설정 파일 경로 등 properties에 설정합니다. app.properties 메뉴 구조properties 조회import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import java.io.IOException;import java.io.InputStream;import java.time
st-d.tistory.com
소스 코드
Runnable task = () -> {
LocalDateTime now = LocalDateTime.now();
LocalTime currentTime = now.toLocalTime();
int currentMinute = currentTime.getMinute();
// 현재 시간이 실행 시간 범위 내에 있는지 확인
if (!currentTime.isBefore(START_TIME) && currentTime.isBefore(END_TIME)) {
if(currentMinute == 0 || currentMinute == 15 || currentMinute == 30 || currentMinute == 45) {
logger.info("현재 시간({})이 실행 범위 내에 있어 작업을 시작합니다.", currentTime.format(TIME_FORMATTER));
executeTask();
}else{
logger.info("00, 15, 30, 45 분이 아닙니다.");
}
} else {
logger.info("현재 시간({})은 실행 범위({} ~ {}) 밖에 있어 작업을 건너뜁니다.",
currentTime.format(TIME_FORMATTER), START_TIME.format(TIME_FORMATTER), END_TIME.format(TIME_FORMATTER));
}
};
전체 소스
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main {
private static final Logger logger = LogManager.getLogger(Main.class);
private static final Properties dbProps = new Properties();
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
// 실행 시작 및 종료 시간 설정
private static final LocalTime START_TIME = LocalTime.of(9, 0, 0);
private static final LocalTime END_TIME = LocalTime.of(18, 0, 0);
static {
try (InputStream input = Main.class.getClassLoader().getResourceAsStream("app.properties")) {
dbProps.load(input);
} catch (IOException ex) {
logger.error("app.properties 파일을 로드하는 데 실패했습니다.", ex);
throw new RuntimeException("설정 파일 로드 실패", ex);
}
}
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
Runnable task = () -> {
LocalDateTime now = LocalDateTime.now();
LocalTime currentTime = now.toLocalTime();
int currentMinute = currentTime.getMinute();
logger.info(">>>>>>>>> {}", currentMinute);
// 현재 시간이 실행 시간 범위 내에 있는지 확인
if (!currentTime.isBefore(START_TIME) && currentTime.isBefore(END_TIME)) {
if(currentMinute == 0 || currentMinute == 15 || currentMinute == 30 || currentMinute == 45) {
logger.info("현재 시간({})이 실행 범위 내에 있어 작업을 시작합니다.", currentTime.format(TIME_FORMATTER));
executeTask();
}else{
logger.info("00, 15, 30, 45 분이 아닙니다.");
}
} else {
logger.info("현재 시간({})은 실행 범위({} ~ {}) 밖에 있어 작업을 건너뜁니다.",
currentTime.format(TIME_FORMATTER), START_TIME.format(TIME_FORMATTER), END_TIME.format(TIME_FORMATTER));
}
};
// 초기 딜레이를 0으로 설정하여 즉시 첫 번째 검사를 시작
scheduler.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS);
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
scheduler.shutdown();
}
}
private static void executeTask() {
Connection oracleConn = null;
PreparedStatement oracleStmt = null;
BufferedReader br = null;
try {
// Oracle 연결
String oracleUrl = dbProps.getProperty("oracle.url");
String oracleUser = dbProps.getProperty("oracle.username");
String oraclePassword = dbProps.getProperty("oracle.password");
String oracleDriver = dbProps.getProperty("oracle.driver");
oracleConn = DriverManager.getConnection(oracleUrl, oracleUser, oraclePassword);
oracleConn.setAutoCommit(false);
String insertQuery = "INSERT INTO your_oracle_table (content) VALUES (?)";
oracleStmt = oracleConn.prepareStatement(insertQuery);
// 텍스트 파일 읽기 및 Oracle 테이블에 삽입
String textFilePath = dbProps.getProperty("textfile.path");
br = new BufferedReader(new FileReader(textFilePath));
String line = "";
int size = 0;
while ((line = br.readLine()) != null) {
oracleStmt.setString(1, line);
oracleStmt.executeUpdate();
size++;
}
oracleConn.commit();
System.out.println(textFilePath + "파일 읽기 및 Oracle 테이블에 insert 완료 - 건수 : " + size + ", 시간 : " + LocalDateTime.now());
} catch (SQLException e) {
logger.error("SQL Exception 발생", e);
if (oracleConn != null) {
try {
oracleConn.rollback();
} catch (SQLException ex) {
logger.error("oracleStmt Exception 발생", ex);
}
}
} catch (IOException e) {
logger.error("텍스트 파일 읽기 오류 발생", e);
if (oracleConn != null) {
try {
oracleConn.rollback();
} catch (SQLException ex) {
logger.error("oracleStmt Exception 발생", ex);
}
}
} finally {
try {
if (br != null) br.close();
} catch (IOException e) {
logger.error("BufferedReader close Exception 발생", e);
}
try {
if (oracleStmt != null) oracleStmt.close();
} catch (SQLException e) {
logger.error("oracleStmtText Exception 발생", e);
}
try {
if (oracleConn != null) oracleConn.close();
} catch (SQLException e) {
logger.error("oracleConn Exception 발생", e);
}
}
}
}
※ 기존 소스에서 시간, 특정 분만 if문 처리 했습니다.
반응형