背景:
同僚告訴我最近一段時間每天上班長時間盯着螢幕工作經常眼睛疼,問我有沒有好用定時提醒功能。我受到啟發,決定用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 nodeconst { 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('').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 ', '填寫一個消息提醒規則例如:*/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 + "", 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/
歡迎試用,提出寶貴意見,如果對你有幫助請幫忙轉發此文章~