1. 前言
日常工作中,长时间对着电脑,眼睛吃不消,适当休息眼睛很重要。就想用NodeJS实现一个定时锁屏小程序,当然有兴趣朋友们,也可以查阅方法,制定windows自带的定时任务。
2. 实现步骤
- Step 1:从NodeJS官网下载NodeJS安装包,官网链接:Node.js 中文网;
- Step 2:npm会随同NodeJS一起安装,然后通过npm安装pm2工具;
npm install -g pm2
- Step 3:复制本文末尾的源码到txt,另存为“护眼.js”文件;
- Step 4:通过pm2,执行“护眼.js”文件;
pm2 start 护眼.js
- Step 5:如果想停止此程序的运行,参考以下命令。
# 列出所用在运行的js小程序
pm2 list
# 找到第一列id,停止对应id的小程序即可
pm2 stop 0
# 也可以直接删除
pm2 delete 0
3. 护眼小程序源码
const child_process = require('child_process');
// 指定锁屏的时间,按自己需求灵活配置
const lock_screen_period_list = [
'09.00.00',
'10.00.00',
'11.00.00',
'12.00.00',
'13.00.00',
'14.00.00',
'15.00.00',
'16.00.00',
'17.00.00',
'18.00.00',
];
const getTime = () => {
const date = new Date();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
let time_str = ''
time_str += (hours < 10 ? '0' + hours : hours) + '.';
time_str += (minutes < 10 ? '0' + minutes : minutes) + '.';
time_str += seconds < 10 ? '0' + seconds : seconds;
return time_str;
}
const task = () => {
const time = getTime();
if (lock_screen_period_list.includes(time)) {
// 真正干活的代码
child_process.exec('rundll32.exe user32.dll,LockWorkStation');
}
};
setInterval(task, 1000);
注:以上,如有不合理之处,还请帮忙指出,大家一起交流学习~