2

我正在使用"electron": "^5.0.0""node-schedule": "^1.3.2"- node-schedule。我正在尝试在启动电子应用程序时加载我的工作队列。

main.js的 from electron 如下所示:

async function main() {

  const {
    app,
    BrowserWindow
  } = require('electron')
  const schedule = require('node-schedule');
  const {
    Schedule
  } = require('./schedule')

  let win

  let sch = new Schedule()
  try {
    await sch.initScheduledContent()
    console.log("Imported of jobs done!");
  } catch (error) {
    console.log(error);
  }

  function createWindow() {
    win = new BrowserWindow({
      width: 800,
      height: 600
    })
    win.loadFile('index.html')
    win.on('closed', () => {
      win = null
    })
  }

  app.on('ready', createWindow)

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })

  app.on('activate', () => {
    if (win === null) {
      createWindow()
    }
  })
}

main()

我的schedule.js样子如下:

const schedule = require('node-schedule');

class Scheduler {

    constructor(){}

    randomDate(start, end) {
        return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
    }

    async initScheduledContent() {
        let start = new Date()
        let end = new Date()
        end.setSeconds(end.getSeconds() + 20) // add 20 seconds to current time

        let arr = []
        const numb_jobs = 50
        for (let i = 0; i < numb_jobs; i++) {
            d = randomDate(start, end)
            arr.push([i, d]) // job_number, date
            console.log('OPEN: Job  -- #' + arr[i][0] + ' -- scheduled at: ' + arr[i][1]);

            schedule.scheduleJob(arr[i][1], function () {
                console.log('DONE: Job -- #' + arr[i][0] + ' -- executed at: ' + arr[i][1]);
            });
        }
        console.log("\n Number of Jobs Scheduled: " + Object.keys(this.getQueue()).length + "\n");
    }
}

module.exports = {
    Scheduler
};

使用时electron .,我的应用程序无法启动并挂断。

有什么建议如何启动我的应用程序并将所有作业加载到队列中?

4

1 回答 1

4

不要用等待阻塞主进程..

而是在里面调用它app.on('ready', async () => {/* so your schedule process then call createWindow */}

并且不要在函数中编写所有内容..

现在您可以将 async 分配给 on.ready 函数..

替代解决方案

做这样的事情

创建 mainWindow 然后通过 ipcRenderer 在 main 中调用您的调度程序。

这应该工作..

如果没有创建窗口,那么它一定是你在某个地方的错误..

ipcRendrer 的代码示例

// main.js

const {ipcMain} = require('electron')

/* start app, createWindow and all other code */

ipcMain.on('scheduler', (event, dataPassedFromRenderer) => {
  /* do your schedule work */

  // pass any data asynchronously to renderer process with
  event.sender.send('scheduler', returnData) 
}

现在在渲染器代码中

/* renderer.js in html or required file in html */

const {ipcRenderer} = require('electron')

// this will send event in main.js
ipcRederer.send('scheduler', 'send any type of data, can be left blank')

// this will listen for any response or event from main.js
ipcRederer.on('scheduler', (event, data) => {/* do if required */})



于 2019-05-03T19:48:36.367 回答