electron实现定时关机和提醒
做个定时关机和提醒的小练习。
- html部分
<body>
<form id="myForm">
<label for="shutdowntime">设置定时关机时间:</label>
<input type="time" id="shutdowntime" value="18:00" name="shutdowntime">
<input type="button" id="myButton" click="startTime()" value="开始生效">
</form>
<p id="remainTime"></p>
<script src="renderer.js"></script>
</body>
- main.js里引入提醒和主进程,在ready中进行监听。
const { app, BrowserWindow,ipcMain,Notification } = require('electron')
const NOTIFICATION_TITLE = '提醒'
const NOTIFICATION_BODY = '还有10分钟即将关闭电脑,请保存数据。'
app.whenReady().then(() => {
//其他方法省略
ipcMain.on('shutdown', () => {
exec('shutdown -s', (err, stdout, stderr) => {
if (err) {
console.error(`执行出错: ${err}`);
return;
}
console.log(`标准输出: ${stdout}`);
console.error(`标准错误: ${stderr}`);
});
});
ipcMain.on('notice', () => {
new Notification({ title: NOTIFICATION_TITLE, body: NOTIFICATION_BODY }).show()
});
})
- renderer.js引入ipcRenderer进程,通过ipcRenderer.send()调用主进程方法。
const { ipcRenderer } = require('electron');
var shutdowntime;
//计时,并处理提醒和关机
function displayTime() {
const now = new Date();
let startTime =now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
let endTime = shutdowntime+':00';
let remainingTime = calculateTimeDifference(startTime, endTime);
var remainTime = "距离关机时间: " + remainingTime;
document.getElementById("remainTime").innerHTML = remainTime;
//到时间提醒
if(remainingTime==='00:10:00'){
ipcRenderer.send('notice');
}
//到时间关机
if(remainingTime==='00:01:00'){
ipcRenderer.send('shutdown');
}
}
//监听设置的事件
document.addEventListener('DOMContentLoaded', function() {
var button = document.getElementById('myButton');
button.addEventListener('click', function() {
// 设置定时器,每秒调用一次displayTime函数
var form = document.getElementById('myForm');
shutdowntime = form.elements['shutdowntime'].value;
setInterval(displayTime, 1000);
});
});
//计算时间差
function calculateTimeDifference(startTime, endTime) {
function toMilliseconds(timeString) {
let parts = timeString.split(':');
let milliseconds = Number(parts[0]) * 3600000 +
Number(parts[1]) * 60000 +
Number(parts[2]) * 1000;
return milliseconds;
}
function toTimeString(milliseconds) {
let hours = Math.floor(milliseconds / 3600000);
let minutes = Math.floor((milliseconds % 3600000) / 60000);
let seconds = Math.floor((milliseconds % 60000) / 1000);
return hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0');
}
let startMillis = toMilliseconds(startTime);
let endMillis = toMilliseconds(endTime);
let differenceMillis = Math.abs(endMillis - startMillis);
return toTimeString(differenceMillis);
}