Spring

Spring 일지 #65 (20211005) 스케쥴링

uni5948 2021. 10. 8. 20:38

65. 스케쥴링

-스케쥴링(*원하는 시간에 원하는 기능을 실행해준다.)

 *패키지 생성

스케쥴러 패키지 생성

 

 * MyScheduler.java 생성

 

MyScheduler.java 생성

 

package com.example.scheduler;

더보기

 

import java.util.Date;

 

import com.example.entity.Item;

import com.example.repository.ItemRepository;



import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

 

@Component

public class MyScheduler {

 

    @Autowired

    ItemRepository iRepository;

 

    // cron tab

    // 초(0-59) 분(0-59) 시(0-23) 일(1-30 or 31) 월(1-12) 요일(0-6)

    // "0 0 * * * *" => 1시간 단위

    // "0 0 8-10 * * *" => 8~10시 정각 실행

    // "0 0 6,19 * * *" => 오전 6시, 오후 7시에 실행

    // "0 0 9-17 * * MON-FRI" => 오전 9시~오후5시 월~금 실행

    @Scheduled(cron = "0 0 * * * *")    // 1 시간 마다

    public void printDate() {

        System.out.println(new Date().toString());

        Item item = iRepository.findById(44L).orElse(null);

        System.out.println(item.toString());

    }

}

 

 * 스케쥴러 패키지 등록(Boot20211005Application.java)

 * 스케쥴러 주석달기 @EnableScheduling

 

package com.example.boot_20211005;

더보기

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.autoconfigure.domain.EntityScan;

import org.springframework.boot.builder.SpringApplicationBuilder;

import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import org.springframework.scheduling.annotation.EnableScheduling;

 

@EnableScheduling

@SpringBootApplication

@EntityScan(basePackages = { "com.example.entity" })

@EnableJpaRepositories(basePackages = { "com.example.repository" })

@ComponentScan(basePackages = { "com.example.controller""com.example.security""com.example.jwt",

        "com.example.service""com.example.scheduler" })

public class Boot20211005Application extends SpringBootServletInitializer {

 

    public static void main(String[] args) {

        SpringApplication.run(Boot20211005Application.classargs);

        System.out.println("start");

    }

 

    @Override

    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {

        return builder.sources(Boot20211005Application.class);

    }

}

 

*출력 확인

출력 확인