-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
101 lines (85 loc) · 2.44 KB
/
main.js
File metadata and controls
101 lines (85 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path");
const schedule = require("node-schedule");
const db = require("./db");
let win;
function createWindow() {
win = new BrowserWindow({
width: 1000,
height: 700,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
},
});
// Dev server (React)
win.loadURL("http://localhost:5173");
win.webContents.openDevTools();
}
app.whenReady().then(() => {
createWindow();
// Re-schedule pending tasks on startup
db.all("SELECT * FROM schedules WHERE status='pending'", [], (err, rows) => {
if (err) {
console.error("Failed to load tasks:", err);
return;
}
if (rows?.length) {
rows.forEach((task) => scheduleJobFromDB(task));
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit();
});
/* ---------------- IPC HANDLERS ---------------- */
// 1. Schedule new task
ipcMain.handle("schedule-task", async (_, { task, runAt }) => {
return new Promise((resolve, reject) => {
db.run(
"INSERT INTO schedules (task, runAt, status) VALUES (?, ?, ?)",
[task, runAt, "pending"],
function (err) {
if (err) {
console.error("Failed to insert task:", err);
return reject(err);
}
const newTask = { id: this.lastID, task, runAt, status: "pending" };
scheduleJobFromDB(newTask);
resolve(newTask);
}
);
});
});
// 2. Get all tasks
ipcMain.handle("get-tasks", async () => {
return new Promise((resolve, reject) => {
db.all("SELECT * FROM schedules ORDER BY runAt ASC", [], (err, rows) => {
if (err) {
console.error("Failed to fetch tasks:", err);
return reject(err);
}
resolve(rows);
});
});
});
/* ---------------- Helper ---------------- */
function scheduleJobFromDB(task) {
const runDate = new Date(task.runAt);
if (isNaN(runDate.getTime())) {
console.error("Invalid date for task:", task);
return;
}
schedule.scheduleJob(runDate, () => {
db.run("UPDATE schedules SET status='done' WHERE id=?", [task.id], (err) => {
if (err) console.error("Failed to update task:", err);
});
if (win?.webContents) {
win.webContents.send("task-executed", task);
}
});
}