专业的编程技术博客社区

网站首页 > 博客文章 正文

如何用Nodejs编写一个定时消息提醒应用?

baijin 2024-08-22 09:18:14 博客文章 5 ℃ 0 评论

背景:

同事告诉我最近一段时间每天上班长时间盯着屏幕工作经常眼睛疼,问我有没有好用定时提醒功能。我受到启发,决定用nodejs来实现一个定时提醒应用。

需求分析:

同事是个程序员,熟悉命令行操作,这样我就可以忽略用户界面了。只要着重实现几个个核心功能点就行。例如:创建消息提醒计划,管理计划等。拆解一下需求,实现这些功能点我会用到【消息提醒】【定时计划】【常驻系统后台】【封装成 node package】。分析的差不多了,接下来就可以准备着手细化实现方案了。


关于消息提醒:

node-notifier 是一个node package,支持发送跨平台【macOS , win, Linux】的native notifications。示例代码:

 const notifier = require('node-notifier');// Stringnotifier.notify('Message');
 Objectnotifier.notify({  title: 'My notification',  message: 'Hello, there!'});


macOS演示效果:

关于定时计划

node-schedule 是一个处理任务调度的package,可以让任务按照指定的时间周期计划来执行。指定时间周期的方式和cron类似。如下为周期指定的方法:


*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    │
│    │    │    │    │    └ 周几(0 - 7)(0 或 7 是周日)
│    │    │    │    └───── 月(1 - 12)
│    │    │    └────────── 日(1 - 31)
│    │    └─────────────── 小时(0 - 23)
│    └──────────────────── 分钟(0 - 59)
└───────────────────────── 秒(0 - 59, 可选)


node-schedule代码示例:

const schedule = require('node-schedule');
schedule.scheduleJob('0 0 9-18 * * 1-5', function () {
//周一到周五9-18点每小时0分0秒执行任务
})

关于常驻系统后台:


想要让程序一直监听schedule,就要在系统中开启一个常驻的nodejs进程。利用nodejs自带的child_process 模块创建node子进程。其他的守护进程包也都是通过child_process来实现的例如:foreverjs,PM2等。

示例代码up.js:


const { spawn } = require('child_process');const path = require('path');const { exit } = require('process');// 开启node子进程let child = spawn('node', [path.join(__dirname, 'task.js'), options.rule])// 退出父进程exit();

开启进程之后可以在活动监视器查看到,如图所示:

接下来要完成命令交互部分,命令行交互用到是的commanderjs这个package。使用它我们可以快速实现命令交互的功能。代码示例 up:

#!/usr/bin/env node
const { exec, spawn } = require('child_process');
const { exit } = require('process');
const program = require('commander');
var fs = require('fs');
const kill = require('tree-kill');
const path = require('path');

const log_file = path.join(__dirname, 'log.txt')

const stop = program.command('stop');
stop.action(() => {
  let pids = fs.readFileSync(log_file).toString().trim()
  if (pids.length != 0) {
    pids.split('\n').forEach(function (pid) {
      if (pid.length > 0) {
        kill(pid)
        fs.writeFile(log_file, '', function () { })
      }
    })
    console.log('?提醒已经关闭')
  } else {
    console.log("??没有发现任何计划")
  }

})


const start = program.command('start')

start.requiredOption('-r, --rule <type>', '填写一个消息提醒规则例如:*/30 * * * * *')
  .action(function (options) {
    try {
      let child = spawn('node', [path.join(__dirname, 'task.js'), options.rule])
      fs.open(log_file, 'a+', function (err, fd) {
        fs.write(fd, child.pid + "\n", function () { });
        exit();
      });
      console.log(`?任务创建成功,执行频率${options.rule}`);
    } catch (e) {
      console.error('spawn ERROR !!');
      console.error(e);
    }
  })


program.parse(process.argv);


到此位置功能已经基本实现了,我已经把package发布到了npm和Github(目前支持macOS,其他平台还没有测试)。

安装:

npm i standup-workday -g

开启消息定时提醒命令:

up start  -r "*/10 * * * * *" 

关闭:

up stop

视频演示地址:https://www.ixigua.com/6864153350209241607/

欢迎试用,提出宝贵意见,如果对你有帮助请帮忙转发此文章~

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表