반응형

아래는 이 글의 동영상 강의입니다.

https://youtu.be/5FiFW_057KU

 

 

서버를 운영하다보면 정기적으로 Job을 실행해야 하는 경우가 생깁니다.

이럴때 정기적으로 Job을 자동으로 실행해 주는 것을 스케줄러라고 합니다.

 

nodejs에서는 node-shedule이라는 패키지를 사용하면 스케줄러를 쉽게 만들 수 있습니다.

node express 에서 scheduler를 만드는 방법을 알아 보겠습니다.

 

우선 node 프로젝트를 생성합니다.

node init -y

프로젝트에 express를 추가합니다.

npm i express

app.js 파일을 만들고 다음 내용을 추가합니다.

const express = require('express')
const app = express()

app.get('/', function (req, res) {
  res.send('Hello World')
})

app.listen(3000)

서버를 실행합니다.

node app

브라우저 주소창에 http://localhost:3000을 입력하고 "Hello World"가 나오는지 확인 합니다.

 

스케줄러를 만들기 위해 사용할 패키지를 다음 url에서 확인합니다.

https://github.com/node-schedule/node-schedule

 

GitHub - node-schedule/node-schedule: A cron-like and not-cron-like job scheduler for Node.

A cron-like and not-cron-like job scheduler for Node. - GitHub - node-schedule/node-schedule: A cron-like and not-cron-like job scheduler for Node.

github.com

 

프로젝트에 node-schedule을 설치합니다.

npm i node-schedule

app.js에 다음 내용을 추가합니다.

const schedule = require('node-schedule');
const express = require('express');
const app = express();

app.get('/', function (req, res) {
  res.send('Hello World');
})

app.listen(3000, function(){
    console.log('Express start on port 3000!');
    schedule.scheduleJob('* * * * * *', function(){
        console.log('The answer to life, the universe, and everything!');
    });
});

프로그램을 실행합니다.

node app

실행 결과는 다음과 같습니다.

스케쥴일 1초 마다 수행되는 것을 확인할 수 있습니다.

 

스케줄을 설정하는 법은 다음과 같습니다.

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    │
│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
│    │    │    │    └───── month (1 - 12)
│    │    │    └────────── day of month (1 - 31)
│    │    └─────────────── hour (0 - 23)
│    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)

앞에서 부터 초, 분, 시, 일, 월, 요일의 순입니다.

지속적인 실행은 *를 사용하면됩니다.

특정 시간에 실행하는 것은 아래와 같이 작성하면됩니다.

  • 매초 실행 : * * * * * *
  • 매분 실행 : * * * * *
  • 매분 0초에 실행 : 0 * * * * *
  • 매분 10초에 실행 : 10 * * * * *
  • 매시 1분 10초에 실행 : 10 1 * * * * 

다음은 매분 0초에 실행하도록 변경한 예입니다.

app.listen(3000, function(){
    console.log('Express start on port 3000!');
    schedule.scheduleJob('0 * * * * *', function(){
        console.log(new Date() + ' scheduler running!');
    });
});

실행 결과는 다음과 같습니다.

이상으로  Express에서 스케줄러를 만드는 방법이었습니다.

반응형

+ Recent posts