[Practice] 스케쥴러 활용 (1)

2021. 4. 20. 16:58Spring/Practice

1. 문제

  • 스프링 스케쥴러를 이용하여 매일 새벽 4시에 로그 정보를 삭제하는 기능

 

 

 

2. 풀이

- data.sql

INSERT INTO LOGS(ID, TEXT, REG_DATE) VALUES
    (1, '로그1', '2021-01-01 01:01:01.000000'),
    (2, '로그2', '2021-01-01 01:02:01.000000'),
    (3, '로그3', '2021-01-01 01:03:01.000000'),
    (4, '로그4', '2021-01-01 01:04:01.000000'),
    (5, '로그5', '2021-01-01 01:05:01.000000');

- LogService.java

package com.example.jpa.sample.logs.service;

public interface LogService {

    void add(String text);

    void deleteLog();

}

- LogServiceImpl.java

package com.example.jpa.sample.logs.service;

import com.example.jpa.sample.logs.entity.Logs;
import com.example.jpa.sample.logs.repository.LogsRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@RequiredArgsConstructor
@Service
public class LogServiceImpl implements LogService {

    private final LogsRepository logsRepository;

    @Override
    public void add(String text) {

        logsRepository.save(Logs.builder()
                .text(text)
                .regDate(LocalDateTime.now())
                .build());
    }

    @Override
    public void deleteLog() {
        logsRepository.deleteAll();
    }
}

- MainApplication.java

package com.example.jpa.sample;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling // 스케쥴러 설정
@EnableAspectJAutoProxy // aop 동작 설정
@SpringBootApplication
public class SampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }

}

- Scheduler.java

package com.example.jpa.sample.common.schedule;

import com.example.jpa.sample.logs.service.LogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@RequiredArgsConstructor
@Component
public class Scheduler {

    private final LogService logService;

//    @Scheduled(cron = "0 0 4 * * *") // 새벽 4시
    @Scheduled(fixedDelay = 1000 * 60) // 1분에 한번씩 실행
    public void deleteLog() {
        log.info("스케쥴 실행");
        logService.deleteLog();
    }
}
728x90

'Spring > Practice' 카테고리의 다른 글

[Practice] 스케쥴러 활용 (2)  (0) 2021.04.20
[Practice] 메일 전송 (4)  (0) 2021.04.20
[Practice] 메일 전송 (3)  (0) 2021.04.20
[Practice] 메일 전송 (2)  (0) 2021.04.20