Energy efficient long polling in macOS
Or, more things I encountered when going to macOS from iOS
Making my way to macOS I decided to make a simple status bar app that will check all the movies in iTunes priced at $0.99. You can take quick look here 😘 (go ahead, it’s free). One of my requirements for this app was to make it consume the least amount of power possible, given that in theory will be open 24/7 on someone’s computer.
In order to do this I looked into iOS equivalents of long polling in macOS, but found something a bit better NSBackgroundActivityScheduler
. This class enables you to schedule task in the background repeatedly, which is exactly what I needed in order to constantly check when new deals are available.
NSBackgroundActivityScheduler
The implementation is probably one of the most trivial things I have encountered lately. A single method with a callback, this app is doing something like this:
schedule
blockThe only thing that stands out here is the shouldDefer
which is just us being a good developer and deferring the execution of this code to a later time (if we can). With that simple block of code the method yourScheduledTask
will be called approximately(1) every 4 hours, and then we just handle the block passed to us like so.
That is all 👋. Get in touch on Twitter: @raulriera
Note
(1) While creating this app, it appears that NSBackgroundActivityScheduler
is only executed when the computer is connected to a power source. Keep that in mind if you want to schedule really important business logic.