Node.js定时任务实现:每日9点至21点每15分钟写入数据库
实现每日9:00-21:00每15分钟写入数据库的定时任务
这个需求属于周期性定时任务+时间窗口限制,下面按不同技术栈给出具体实现方案:
一、Java(Spring Boot 环境)
利用Spring自带的@Scheduled注解,结合cron表达式或时间判断即可实现。
方式1:精准Cron表达式
直接编写符合时间范围的cron规则,覆盖9:00到21:00的每15分钟节点:
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; @Component public class DbSyncTask { private final DataSource dataSource; // 构造注入数据源 public DbSyncTask(DataSource dataSource) { this.dataSource = dataSource; } // cron规则:0秒、每15分钟、9-21点、任意日期/月份/星期 @Scheduled(cron = "0 */15 9-21 * * ?") public void writeToDatabase() { String sql = "INSERT INTO your_table (data_time, content) VALUES (?, ?)"; try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { // 示例参数:当前时间戳、固定内容 stmt.setLong(1, System.currentTimeMillis()); stmt.setString(2, "定时任务写入数据"); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); // 此处可添加日志记录或异常告警逻辑 } } }
注意:需在Spring Boot启动类上添加@EnableScheduling注解开启定时任务功能。
方式2:基础定时+时间范围判断
若不想编写复杂cron,可设置每15分钟执行一次,再在方法内校验时间窗口:
@Scheduled(fixedRate = 15 * 60 * 1000) // 每15分钟执行一次 public void writeToDbWithCheck() { int currentHour = java.time.LocalDateTime.now().getHour(); if (currentHour >= 9 && currentHour <= 21) { // 执行数据库写入逻辑,同方式1中的代码 } }
二、Python(APScheduler 框架)
APScheduler是Python生态中常用的定时任务工具,支持多种触发器类型。
首先安装依赖:
pip install apscheduler
代码示例(以PostgreSQL为例):
from apscheduler.schedulers.blocking import BlockingScheduler import psycopg2 from datetime import datetime def write_to_db(): conn = None try: conn = psycopg2.connect( dbname="your_db", user="your_user", password="your_pwd", host="localhost" ) cur = conn.cursor() sql = "INSERT INTO your_table (data_time, content) VALUES (%s, %s)" cur.execute(sql, (datetime.now(), "定时任务写入数据")) conn.commit() cur.close() except Exception as e: print(f"写入失败: {str(e)}") if conn: conn.rollback() finally: if conn: conn.close() if __name__ == "__main__": scheduler = BlockingScheduler() # 添加cron触发器:每15分钟、9-21点、每天执行 scheduler.add_job( write_to_db, 'cron', minute='*/15', hour='9-21', id='db_write_job' ) try: scheduler.start() except KeyboardInterrupt: scheduler.shutdown()
三、Node.js(node-schedule 库)
node-schedule是Node.js环境下轻量且灵活的定时任务库。
先安装依赖:
npm install node-schedule mysql2
代码示例:
const schedule = require('node-schedule'); const mysql = require('mysql2/promise'); // 数据库连接配置 const dbConfig = { host: 'localhost', user: 'your_user', password: 'your_pwd', database: 'your_db' }; async function writeToDb() { let connection; try { connection = await mysql.createConnection(dbConfig); const [rows] = await connection.execute( 'INSERT INTO your_table (data_time, content) VALUES (?, ?)', [Date.now().toString(), '定时任务写入数据'] ); console.log(`写入成功,影响行数: ${rows.affectedRows}`); } catch (err) { console.error('写入失败:', err); } finally { if (connection) { await connection.end(); } } } // 定义定时规则:每15分钟、9-21点执行 const rule = new schedule.RecurrenceRule(); rule.minute = new schedule.Range(0, 59, 15); rule.hour = new schedule.Range(9, 21); // 启动定时任务 schedule.scheduleJob(rule, writeToDb); console.log('定时任务已启动,将在每日9:00-21:00每15分钟写入数据库');
通用注意事项
- 连接池优化:高频任务建议使用数据库连接池,避免重复创建/销毁连接的性能损耗。
- 异常处理:必须添加异常捕获与日志记录,必要时增加告警机制(如邮件、企业微信通知)。
- 幂等性保障:确保任务重复执行时不会产生重复数据,可通过唯一标识或数据库唯一约束实现。
- 生产环境可靠性:若部署到生产环境,建议采用分布式任务调度框架(如Java的XXL-JOB、Python的Celery+Beat),避免单点故障。
内容的提问来源于stack exchange,提问作者Uday kiran
相关产品推荐
相关产品推荐

