Commit 26c55257 by linjinhong

feat:修改定时任务方法

parent 98eefb15
...@@ -5,7 +5,7 @@ import { createProtocol } from "vue-cli-plugin-electron-builder/lib"; ...@@ -5,7 +5,7 @@ import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import { createServer } from "@/server/index.js"; import { createServer } from "@/server/index.js";
import { autoUpdater } from "electron-updater"; import { autoUpdater } from "electron-updater";
const { createBatchDownloadQueue } = require("@/utils/download-queue"); import downloadQueue from "@/utils/download-queue";
const fs = require("fs"); const fs = require("fs");
import path from "path"; // 引入 path 模块 import path from "path"; // 引入 path 模块
...@@ -30,36 +30,6 @@ const winURL = ...@@ -30,36 +30,6 @@ const winURL =
? "http://localhost:8050" ? "http://localhost:8050"
: `file://${__dirname}/index.html`; : `file://${__dirname}/index.html`;
// 全局唯一下载队列,服务启动时初始化一次
const downloadQueue = createBatchDownloadQueue({
concurrency: 3,
retryTimes: 2,
basePath: "",
// 单文件下载成功
onSuccess: task => {
win.webContents.send("download:file-success", {
batchArrangeNum: task.batchArrangeNum,
fileName: task.fileName
});
},
// 单文件下载失败
onError: (task, err) => {
win.webContents.send("download:file-error", {
batchArrangeNum: task.batchArrangeNum,
fileName: task.fileName,
msg: err.message
});
},
// 批次校验失败(新增:返回所有异常批次)
onBatchInvalid: invalidList => {
win.webContents.send("download:batch-invalid", invalidList);
},
// 全部任务完成
onIdle: () => {
win.webContents.send("download:all-finish");
}
});
async function createWindow() { async function createWindow() {
win = new BrowserWindow({ win = new BrowserWindow({
width: 1500, width: 1500,
...@@ -408,6 +378,15 @@ async function createWindow() { ...@@ -408,6 +378,15 @@ async function createWindow() {
); );
}); });
// 监听窗口的 reload 事件
win.webContents.on("did-finish-load", () => {
const { width, height } = win.getBounds();
win.webContents.send("window-size", { width, height });
console.log(99999);
// downloadQueue.startAutoDownloadTask();
});
if (process.env.WEBPACK_DEV_SERVER_URL) { if (process.env.WEBPACK_DEV_SERVER_URL) {
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL); await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
if (!process.env.IS_TEST) win.webContents.openDevTools(); if (!process.env.IS_TEST) win.webContents.openDevTools();
...@@ -508,17 +487,7 @@ async function createWindow() { ...@@ -508,17 +487,7 @@ async function createWindow() {
win.on("resize", () => { win.on("resize", () => {
const { width, height } = win.getBounds(); const { width, height } = win.getBounds();
win.webContents.send("window-size", { width, height }); win.webContents.send("window-size", { width, height });
}); console.log(888);
// 监听窗口的 reload 事件
win.webContents.on("did-finish-load", () => {
const { width, height } = win.getBounds();
win.webContents.send("window-size", { width, height });
});
// IPC 通信
ipcMain.on("download:submit-batch-list", (event, list) => {
downloadQueue.addBatchList(list);
event.returnValue = { code: 200, msg: "已处理" };
}); });
ipcMain.on("get-install-path", event => { ipcMain.on("get-install-path", event => {
...@@ -542,18 +511,9 @@ async function createWindow() { ...@@ -542,18 +511,9 @@ async function createWindow() {
} }
}); });
ipcMain.on("download:get-status", event => { // ========== 新增3:窗口关闭时停止定时任务 ==========
try { win.on("closed", () => {
// 无论正常异常都保证回复,避免前端挂起 downloadQueue.stopAutoDownloadTask();
event.reply("download:status-reply", {
isRunning: downloadQueue.isRunning
});
} catch (err) {
event.reply("download:status-reply", {
isRunning: false,
error: err.message
});
}
}); });
} }
...@@ -587,8 +547,11 @@ app.on("will-quit", () => { ...@@ -587,8 +547,11 @@ app.on("will-quit", () => {
globalShortcut.unregister("F5"); globalShortcut.unregister("F5");
globalShortcut.unregister("CommandOrControl+R"); globalShortcut.unregister("CommandOrControl+R");
}); });
app.on("before-quit", () => { app.on("window-all-closed", () => {
downloadQueue.destroy(); downloadQueue.stopAutoDownloadTask();
if (process.platform !== "darwin") {
app.quit();
}
}); });
if (isDevelopment) { if (isDevelopment) {
......
...@@ -75,7 +75,7 @@ function readEnv() { ...@@ -75,7 +75,7 @@ function readEnv() {
fileEnv = config.fileApiUrl; fileEnv = config.fileApiUrl;
env = config.apiApiHost; env = config.apiApiHost;
visionUrl = config.visionUrl; visionUrl = config.visionUrl;
console.log("配置加载完成:", { fileEnv, env, visionUrl }); // console.log("配置加载完成:", { fileEnv, env, visionUrl });
} catch (err) { } catch (err) {
console.error("读取配置文件失败:", err); console.error("读取配置文件失败:", err);
......
import axios from "axios";
import Store from "electron-store"; // 主进程用 electron-store 存取用户信息,和渲染进程的 $dataStore 数据互通
const dataStore = new Store();
// 纯请求实例:无任何 UI 依赖,仅处理 token 注入和错误格式化
const service = axios.create({
baseURL: "http://localhost:3000",
timeout: 12600000
});
// 请求拦截:仅注入 token
service.interceptors.request.use(
config => {
const user = dataStore.get("user");
if (user.token) {
config.headers["jwt-token"] = user.token;
}
return config;
},
error => Promise.reject(error)
);
// 响应拦截:仅处理数据和错误信息,不做任何 UI 操作
service.interceptors.response.use(
response => response.data,
error => {
let errMsg = "请求失败,请稍后重试";
if (error.response.data) {
const data = error.response.data;
errMsg =
data.msg || data.message || `请求错误(${error.response.status})`;
} else if (error.message) {
errMsg = error.message.includes("timeout")
? "请求超时,请检查网络"
: error.message;
}
return Promise.reject(new Error(errMsg));
}
);
export default service;
...@@ -179,10 +179,7 @@ export default { ...@@ -179,10 +179,7 @@ export default {
<div class="page-header"> <div class="page-header">
<el-form style="display: flex;flex-wrap: nowrap;" inline> <el-form style="display: flex;flex-wrap: nowrap;" inline>
<el-form-item> <el-form-item>
<el-button <el-button icon="el-icon-arrow-left" @click="goBack"
icon="el-icon-arrow-left"
@click="goBack"
style="margin-right:12px;"
>返回</el-button >返回</el-button
></el-form-item ></el-form-item
> >
...@@ -194,7 +191,12 @@ export default { ...@@ -194,7 +191,12 @@ export default {
></el-input ></el-input
></el-form-item> ></el-form-item>
<el-form-item label="操作单状态"> <el-form-item label="操作单状态">
<el-select v-model="searchForm.status" placeholder="请选择" clearable> <el-select
style="width: 120px;"
v-model="searchForm.status"
placeholder="请选择"
clearable
>
<el-option <el-option
v-for="(value, label) in statusMap" v-for="(value, label) in statusMap"
:key="value" :key="value"
...@@ -203,7 +205,12 @@ export default { ...@@ -203,7 +205,12 @@ export default {
></el-option> </el-select ></el-option> </el-select
></el-form-item> ></el-form-item>
<el-form-item label="操作单排版状态"> <el-form-item label="操作单排版状态">
<el-select v-model="searchForm.layout" placeholder="请选择" clearable> <el-select
v-model="searchForm.layout"
placeholder="请选择"
clearable
style="width: 120px;"
>
<el-option label="排版成功" :value="true"></el-option> <el-option label="排版成功" :value="true"></el-option>
<el-option label="排版失败" :value="false"> </el-option> </el-select <el-option label="排版失败" :value="false"> </el-option> </el-select
></el-form-item> ></el-form-item>
......
<script> <script>
import BaseTable from "../../components/BaseTable.vue"; import BaseTable from "../../components/BaseTable.vue";
const { remote, ipcRenderer } = require("electron"); const { remote, ipcRenderer } = require("electron");
const { getDTFSetting } = require("@/server/utils/store"); const { getDTFSetting, setDTFSetting } = require("@/server/utils/store");
const { Menu } = remote; const { Menu } = remote;
const path = require("path"); const path = require("path");
const { pathMap } = require("@/config/index.js"); const { pathMap } = require("@/config/index.js");
...@@ -26,7 +26,7 @@ export default { ...@@ -26,7 +26,7 @@ export default {
searchForm: {}, searchForm: {},
radio: "", radio: "",
templateBatchArrangeNum: "", templateBatchArrangeNum: "",
pollTimer: null,
dtfSetting: getDTFSetting(), dtfSetting: getDTFSetting(),
isFetching: false, isFetching: false,
pageInfo: { pageInfo: {
...@@ -107,63 +107,25 @@ export default { ...@@ -107,63 +107,25 @@ export default {
}; };
}, },
mounted() { mounted() {
this.loadLocalConfig();
this.fetchBatchList(); this.fetchBatchList();
this.pollTimer = setInterval(() => this.fetchBatchList(), 300000);
// 单文件下载成功
ipcRenderer.on("download:file-success", (_, data) => {
console.log(`批次 ${data.batchArrangeNum}${data.fileName} 下载完成`);
});
// 单文件下载失败
ipcRenderer.on("download:file-error", (_, data) => {
this.$message.error(
`批次 ${data.batchArrangeNum}${data.fileName} 下载失败,${data.msg}`
);
});
// 新增:批次校验失败,批量提示
ipcRenderer.on("download:batch-invalid", (_, invalidList) => {
const msg = invalidList
.map(item => `【${item.batchArrangeNum}${item.reason}`)
.join(";");
this.$message.warning(`存在异常批次:${msg}`);
});
},
beforeDestroy() {
if (this.pollTimer) {
clearInterval(this.pollTimer);
this.pollTimer = null;
}
ipcRenderer.removeAllListeners("download:status-reply");
ipcRenderer.removeAllListeners("download:file-success");
ipcRenderer.removeAllListeners("download:file-error");
ipcRenderer.removeAllListeners("download:batch-invalid");
ipcRenderer.removeAllListeners("download:all-finish");
}, },
methods: { methods: {
getDownloadStatus() { async loadLocalConfig() {
return new Promise(resolve => { try {
// 只监听一次回复,避免重复绑定 if (!getDTFSetting().downloadDir) {
ipcRenderer.once("download:status-reply", (_, status) => { const path = ipcRenderer.sendSync("get-install-path");
resolve(status); setDTFSetting({ downloadDir: path });
}); }
// 发送请求 } catch (error) {
ipcRenderer.send("download:get-status"); console.log(error);
}); }
}, },
//定时任务 //定时任务
async fetchBatchList(value) { async fetchBatchList(value) {
// 先判断:有下载任务在跑,本轮直接跳过
// console.log("this.isFetching", this.isFetching);
if (this.isFetching) return;
this.isFetching = true;
try { try {
const status = await this.getDownloadStatus();
// console.log("status", status);
if (status.isRunning) return;
let params = { let params = {
currentPage: this.pageInfo.currentPage, currentPage: this.pageInfo.currentPage,
pageSize: this.pageInfo.pageSize pageSize: this.pageInfo.pageSize
...@@ -179,12 +141,9 @@ export default { ...@@ -179,12 +141,9 @@ export default {
this.tableList = res.data.records || []; this.tableList = res.data.records || [];
this.pageInfo.total = res.data.total; this.pageInfo.total = res.data.total;
ipcRenderer.sendSync("download:submit-batch-list", this.tableList);
} }
} catch (err) { } catch (err) {
console.error("批次列表拉取失败", err); console.error("批次列表拉取失败", err);
} finally {
this.isFetching = false;
} }
}, },
...@@ -195,7 +154,7 @@ export default { ...@@ -195,7 +154,7 @@ export default {
handleSizeChange(size) { handleSizeChange(size) {
this.pageInfo.pageSize = size; this.pageInfo.pageSize = size;
this.pageInfo.currentPage = 1; this.pageInfo.currentPage = 1;
this.loadData(); this.settingRes();
}, },
handleCurrentChange(page) { handleCurrentChange(page) {
this.pageInfo.currentPage = page; this.pageInfo.currentPage = page;
...@@ -245,6 +204,7 @@ export default { ...@@ -245,6 +204,7 @@ export default {
[3, 5].includes(value.layoutStatus) [3, 5].includes(value.layoutStatus)
) { ) {
this.dialogVisible = true; this.dialogVisible = true;
this.radio = "";
this.templateBatchArrangeNum = value.batchArrangeNum; this.templateBatchArrangeNum = value.batchArrangeNum;
} else { } else {
this.$message( this.$message(
...@@ -305,15 +265,18 @@ export default { ...@@ -305,15 +265,18 @@ export default {
const { data } = await this.$api.post(pathMap["listMaterialsByBatch"], { const { data } = await this.$api.post(pathMap["listMaterialsByBatch"], {
batchArrangeNum: value batchArrangeNum: value
}); });
const newUrls = data.flatMap(el => el.urls);
// console.log(311, newUrls);
// return;
const res = await this.$api.post("/downloadMaterial", { const res = await this.$api.post("/downloadMaterial", {
urls: data.urls, urls: newUrls,
targetPath: path.join( targetPath: path.join(
getDTFSetting().downloadDir, getDTFSetting().downloadDir,
`批次号:${value}`, `批次号:${value}`,
"原素材" "原素材"
) )
}); });
console.log("listMaterialsByBatch-", data); // console.log("listMaterialsByBatch-", data);
console.log("downloadMaterial", res); console.log("downloadMaterial", res);
this.$message("下载进行中,下载完成的素材将在文件夹原素材中显示"); this.$message("下载进行中,下载完成的素材将在文件夹原素材中显示");
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment