You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron:如何避免渲染进程在后台被节流?

Electron后台渲染进程节流问题求助

应用架构与问题现象

我开发了一款接收推送通知的Electron应用,工作流程如下:
主进程通过以下代码启动子进程:

const Engine = fork(path.join(__dirname, 'engine.js'), [], {
  stdio: ['pipe', 'pipe', 'pipe', 'ipc']
})

这些子进程通过Websocket对接多个推送通知服务,运行正常,推送响应几乎即时。

子进程通过Websocket向BrowserWindow创建的渲染进程发送消息以展示通知,渲染端消费代码:

socket.onmessage = m => {
  const { event, payload } = JSON.parse(m.data) // { event: "name", payload: {...} }
  console.log("EVENT:", event)
  switch (event) {
    case "push-notification": showNotification(payload); break;
    ...
  }
  ...
}

渲染进程在前台时一切正常,但后台运行数分钟后出现节流现象:子进程(上述Engine)的带时间戳日志与渲染进程的"EVENT:"日志间隔可达30秒至数分钟。

为排查问题,我在渲染进程中加入定时检查:

let atom = (new Date()).getTime()
window.setInterval(() => {
  if ((new Date()).getTime() > (atom + 60 * 1000)) {
    // clock out of sync
    console.error("CLOCK OUT OF SYNC")
  }
  console.log("Tick. Tock.")
  atom = (new Date()).getTime()
}, 1000)

应用后台运行一段时间后打开,可见"Tick. Tock."消息间隔逐渐变大直至停止,前台化数秒后出现"CLOCK OUT OF SYNC"错误,说明定时器已暂停。

已尝试的无效方案

当前使用Electron 20.0.0,我尝试了以下方案均无效:

  • 主进程启动前添加命令行参数:
// before running any renderers
app.commandLine.appendSwitch('disable-renderer-backgrounding');
app.commandLine.appendSwitch('disable-background-timer-throttling');
app.commandLine.appendSwitch('disable-backgrounding-occluded-windows');
powerSaveBlocker.start('prevent-app-suspension');
  • 创建BrowserWindow时配置:
new BrowserWindow({
  ...
  webPreferences: {
   backgroundThrottling: false,
   ...
  },
  ...
})
  • 渲染进程中创建AudioContext:
const context = new AudioContext()
const source = context.createBufferSource()
source.connect(context.destination)
source.start(0)
  • 主进程手动唤醒窗口:
// where win is a BrowserWindow
win.focus()
await sleep(120); // Promise-based sleep, appr. 2 JS frames
win.minimize()

需求

如何让渲染进程在后台全速运行无延迟?最多可接受10-15秒延迟,也可接受通过主进程手动唤醒/解除节流的方案。

内容的提问来源于stack exchange,提问作者cuuupid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 11:06:48