Back-end
[node.js] schedular
hjr067
2025. 1. 6. 13:58
인턴에 들어가기 앞서 ...
스케줄러 구현 총정리 !
우선 node.js의 일반적인 프로젝트 구조는
jaeryeong-app/
├── src/
│ ├── routes/ # 라우트 정의
│ │ ├── users.js # 사용자 관련 라우트
│ │ └── products.js # 상품 관련 라우트
│ ├── controllers/ # 컨트롤러 (핸들러 로직)
│ │ ├── users.js # 사용자 로직
│ │ └── products.js # 상품 로직
│ ├── middlewares/ # 미들웨어
│ │ └── auth.js # 인증 미들웨어
│ ├── scheduler/ # 스케줄러 관련 코드
│ │ └── backup.js # 파일 백업 스케줄러(이건 예시로 만약 파일 백업 작업을 수행하는 스케줄러일 경우)
│ │ └── notify.js # 주기적인 알림 메세지 보내기 위한 스케줄러
│ ├── models/ # 데이터베이스 모델
│ │ └── user.js # 사용자 모델
│ ├── app.js # Express 앱 설정
│ └── server.js # 서버 실행 파일
├── package.json # 의존성 관리(text file) : git에 포함
└── README.md
이 중 저 scheduler에 대해 모든 걸 탈탈 털어보자 !
src/scheduler/ 디렉토리
- 백그라운드 작업(ex. 주기적 파일 backup, 데이터 동기화 등)을 관리하기 쉽다
Schedular File
예제 : 주기적인 알림 보내기
- 알림 메세지를 콘솔에 출력
- 이후 실제 이메일이나 sms를 보내는 방식으로 확장
npm install node-cron
src/schedular/notify.js
const cron = require('node-cron');
// 알림 메시지 생성 함수
function sendNotification() {
console.log(`[${new Date().toLocaleString()}] 알림: 잊지 말고 오늘의 일을 처리하세요!`);
}
// 스케줄러 설정: 매일 오전 9시에 실행
cron.schedule('0 9 * * *', () => {
sendNotification();
});
console.log("Notification scheduler is running...");
- cron.schedule('0 9 * * *', ...): 매일 오전 9시에 실행
- sendNotification(): 알림 메시지를 보내는 함수 (현재는 콘솔에 출력)
- 이 코드를 실행하면 콘솔에 매일 오전 9시에 알림 메시지가 표시된다
이메일 알림 보내기
알림을 실제 이메일로 보내려면 nodemailer 라이브러리 사용
1) 설치
npm install nodemailer
2) src/schedular/notify.js
const cron = require('node-cron');
const nodemailer = require('nodemailer');
// 이메일 전송 설정
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com', // 발신자 이메일 주소
pass: 'your-email-password' // 발신자 이메일 비밀번호 (앱 비밀번호 권장)
}
});
// 알림 이메일 전송 함수
function sendEmailNotification() {
const mailOptions = {
from: 'your-email@gmail.com', // 발신자 이메일 주소
to: 'recipient-email@example.com', // 수신자 이메일 주소
subject: '주기적인 알림',
text: '안녕하세요! 이 메시지는 주기적인 알림입니다. 중요한 일을 잊지 마세요!'
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error('Error sending email:', error);
} else {
console.log(`Email sent: ${info.response}`);
}
});
}
// 스케줄러 설정: 매일 오전 9시에 이메일 전송
cron.schedule('0 9 * * *', () => {
sendEmailNotification();
});
console.log("Email notification scheduler is running...");
- nodemailer 설정
- service: 'gmail': Gmail SMTP 서버를 사용. 다른 이메일 서비스도 가능 (예: Yahoo, Outlook 등)
- user와 pass: Gmail 계정과 앱 비밀번호를 사용
- sendEmailNotification()
- 이메일 메시지를 구성하고 transporter.sendMail()로 전송
- 스케줄러
- cron.schedule('0 9 * * *', ...): 매일 오전 9시에 이메일을 보냄
SMS
sms는 Twilio와 같은 서비스를 사용할 수 있다.
1) 설치
npm install twilio
2) src/schedular/notify.js
const cron = require('node-cron');
const twilio = require('twilio');
// Twilio 설정
const accountSid = 'your-twilio-account-sid'; // Twilio 계정 SID
const authToken = 'your-twilio-auth-token'; // Twilio 인증 토큰
const client = twilio(accountSid, authToken);
// SMS 알림 전송 함수
function sendSmsNotification() {
client.messages
.create({
body: '안녕하세요! 이 메시지는 주기적인 알림입니다. 중요한 일을 잊지 마세요!',
from: '+1234567890', // Twilio에서 제공하는 발신 번호
to: '+0987654321' // 수신자 전화번호
})
.then(message => console.log(`SMS sent: ${message.sid}`))
.catch(error => console.error('Error sending SMS:', error));
}
// 스케줄러 설정: 매일 오전 9시에 SMS 전송
cron.schedule('0 9 * * *', () => {
sendSmsNotification();
});
console.log("SMS notification scheduler is running...");
- Twilio 설정
- Twilio 계정을 생성하고 accountSid와 authToken을 가져온다
- from: Twilio에서 제공한 발신 번호
- to: 수신자 전화번호
- 스케줄러
- cron.schedule('0 9 * * *', ...): 매일 오전 9시에 SMS를 보냄
서버와 연결
위에서 작성한 notify 스케줄러를 server.js에서 호출
src/server.js
const http = require('http');
const app = require('./app');
// 스케줄러 실행
require('./scheduler/notify'); // 알림 스케줄러 호출
const PORT = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
실행은
node src/server.js
* 관리
계정, Twilio SID/token 등의 정보는 .env에 저장하고 dotenv로 load
npm install dotenv
.env
EMAIL_USER=your-email@gmail.com
EMAIL_PASS=your-email-password
TWILIO_SID=your-twilio-account-sid
TWILIO_AUTH=your-twilio-auth-token
notify.js
require('dotenv').config();
const emailUser = process.env.EMAIL_USER;
const emailPass = process.env.EMAIL_PASS;