Avoid app throttling when Electron is in backgroun

2019-04-06 23:01发布

问题:

Consider the following example:

setInterval(function()
{
   console.log(new Date());
});

If I run it with electron example.js under OS X, it opens up an icon in my dockbar and starts printing out the time on the console. If the app is not focused, however, after a while it starts throttling.

I looked around and found that this is due to OS X power saving strategy. Now, what if I needed it to keep working in background? My app will be a daemon doing a little bit of something every now and then, and I can't have my users blankly staring at my app for ages.

I found out here that I can do

electron.powerSaveBlocker.start('prevent-app-suspension');

Which actually fixes my problem. This however, is quite invasive, since as far as my understanding goes it prevents the system from sleeping at all! I don't need this much, I would just need my app to do something when the computer is active and online without forcing it to stay awake forever.

Isn't there anything in the middle, between having my users keeping the app continuously in the foreground, and making their computer sleepless forever?

回答1:

As per the current docs:

Note: prevent-display-sleep has higher precedence over prevent-app-suspension. Only the highest precedence type takes effect. In other words, prevent-display-sleep always takes precedence over prevent-app-suspension.

For example, an API calling A requests for prevent-app-suspension, and another calling B requests for prevent-display-sleep. prevent-display-sleep will be used until B stops its request. After that, prevent-app-suspension is used.

What this means is that setting prevent-app-suspension to on, will still allow the system to sleep, and simply does what you desire it to. You can however run the function twice, passing both flags, turning both options on. However, as the docs above say, if both are set to on, then the system will not sleep until that flag has been removed.