본문 바로가기

삼분공부/node.js

[Node.js] Node.js에서 node-schedule로 작업 예약

🛠️ node-schedule이란?

node-schedule은 Node.js에서 크론(Cron)처럼 정해진 시간에 작업을 실행할 수 있게 해주는 모듈.

크론만 사용해 봤지 노드 스케쥴러는 처음이다. 

 


📦 설치 방법

npm install node-schedule

🧪 기본 사용법

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

schedule.scheduleJob('*/5 * * * * *', () => {
  console.log('5초마다 실행됩니다!');
});
  • '*/5 * * * * *': 매 5초마다
  • 총 6자리: [초 분 시 일 월 요일]

⏰ 예제 모음

✅ 1. 매일 오전 9시 정각에 실행

schedule.scheduleJob('0 0 9 * * *', () => {
  console.log('매일 아침 9시에 실행!');
});

✅ 2. 매주 월요일 오전 8시 30분에 실행

schedule.scheduleJob('0 30 8 * * 1', () => {
  console.log('매주 월요일 오전 8시 30분에 실행!');
});

요일은 0(일요일) ~ 6(토요일)


✅ 3. 매분 15초에 실행

schedule.scheduleJob('15 * * * * *', () => {
  console.log('매 분 15초에 실행!');
});

✅ 4. 특정 날짜에 한 번만 실행

const date = new Date(2025, 3, 10, 17, 0, 0); // 2025년 4월 10일 오후 5시
schedule.scheduleJob(date, () => {
  console.log('지정된 날짜에 한 번 실행됩니다!');
});

✅ 5. 매일 오후 10시 ~ 11시 사이, 10분 간격 실행

schedule.scheduleJob('0 */10 22 * * *', () => {
  console.log('밤 10시부터 10분 간격으로 실행!');
});

🛑 스케줄 취소하기

 
const job = schedule.scheduleJob('*/10 * * * * *', () => {
  console.log('작업 실행 중...');
});

// 30초 후에 스케줄 취소
setTimeout(() => {
  job.cancel();
  console.log('스케줄 취소됨');
}, 30000);