Menu

node scheduler 만들기

간단한 프로젝트를 진행하면서 스케쥴러 기능이 필요한 경우가 생겼다.
linux 서버라면 cron 을 사용하여 shell script를 작성하였겠지만 window servercron 을 사용할 수가 없었다.
물론 window server 도 가능은 하지만 프로젝트가 node 로 진행되어 스케쥴러도 node 로 만들어 보게 되었다.

검색을 해보니 node-schedule 이라는 패키지가 있었다.
사용법도 간단하여 바로 사용해 보았다.

패키지를 설치 후에

> npm install node-schedule

작성한 샘플 소스 이다.

// sample.schedule1.js
const schedule = require('node-schedule');

/*
* * * * * * 
┬ ┬ ┬ ┬ ┬ ┬ 
│ │ │ │ │ | 
│ │ │ │ │ └ 주중반복시기 (0 - 7) (0 or 7 일요일)
│ │ │ │ └───── 달 (1 - 12)
│ │ │ └────────── 일 (1 - 31)
│ │ └─────────────── 시 (0 - 23)
│ └──────────────────── 분 (0 - 59)
└───────────────────────── 초 (0 - 59, OPTIONAL)
*/

const scheduler = schedule.scheduleJob('*/5 * * * *', () => {  // 5분 실행
    console.log(getToday() + ' call scheduler');
});

function getToday() {
    const today = new Date();

    const year = today.getFullYear();
    const month = ('0' + (today.getMonth() + 1)).slice(-2);
    const day = ('0' + today.getDate()).slice(-2);

    const hours = ('0' + today.getHours()).slice(-2); 
    const minutes = ('0' + today.getMinutes()).slice(-2);
    const seconds = ('0' + today.getSeconds()).slice(-2); 

    return year + '-' + month + '-' + day + ' '
            + hours + ':' + minutes + ':' + seconds;
}

위 처럼 시간 설정도 가능하지만 아래 처럼 직관적으로 설정 가능하다는게 정말 마음에 들었다.

// sample.schedule2.js
const schedule = require('node-schedule');

const job = schedule.scheduleJob({hour: 2, minute: 10}, () => {
    console.log('매일 오전 2시 10분에 실행!!');
})

출처