nodeJS 서버를 사용하는 경우여러 상황이 필요할 수 있다.
그 중 스케쥴링(특정 시간에 작업 수행)이 필요 할 수 있다.
그때 linux등에서 주로 사용하던 cron을 npm 모듈을 설치하여 간단히 반복 실행 하도록 할 수 있다.
nodeJS node-schedule npm 소개 공식 사이트 - https://www.npmjs.com/package/node-schedule
2016년 6월 26일 9시 30분 0초에 수행할 작업을 스케쥴링하려면 schedule.scheduleJob()에 Date객체의 인스턴스를 전달한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var schedule = require('node-schedule'); | |
var date = new Date(2016, 6, 26, 9, 30, 0); | |
// 2016년 6월 26일 9시 30분 0초date 객체 생성 | |
var j = schedule.scheduleJob(data, function(){ | |
console.log('schedule start'); | |
}); |
위와 같이 간단한 코드로 수행이 가능한 것을 볼 수 있다.
그리고 아래 코드와 같이
매 시간 30분 마다 수행할 작업을 스케쥴링을 할 수도 있다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var schedule = require('node-schedule'); | |
var rule = new schedule.RecurrenceRule(); | |
rule.minute = 30; | |
//매 시간 30분 마다 수행 | |
var j = schedule.scheduleJob(rule, function(){ | |
console.log('...'); | |
}); |
또한 아래 코드처럼 Date객체가 아니라 Cron 형식의 선언으로 스케쥴링을 수행할 수도 있다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var schedule = require('node-schedule'); | |
// cron style 작업 | |
var j = schedule.scheduleJob('45 * * * *', function(){ | |
}); |
위와 같이 스케쥴링을 사용하면 다음과 같은 애플리케이션에 적용하여 사용이 가능하다.
* 특정시간에 DB를 정리하기
* nodeJS 서버에서 특정 사이트를 파싱을 할때 시간을 정해서 파싱할 수 있다.
* 날씨api를 사용할 경우 중복되는 호출을 하지 않고 하루 3-4번의 호출로 실시간성을 확보할 수 있다.(날씨는 분단위로 변하지 않으므로.)
* 그외 여러가지 상황
'프로그래밍 > nodeJS' 카테고리의 다른 글
nodeJS에서 GCM notification 구현하기 (2) | 2016.06.25 |
---|