repetitive calls to beginBackgroundTaskWithExpirationHandler - objective-c

I am evaluating some code that is stacking calls to beginBackgroundTaskWithExpirationHandler in a effort to leave a timer in the background. Have to admit that it is a pretty clever idea, but not sure if this is best practice.
So the flow:
Call beginBackgroundTaskWithExpirationHandler with a callback handler
When it returns, do something, then call again
Rinse and repeat, checking for TaskInvalid along the way
I know that 180 seconds is the max time, but that this can be shorter in some cases.
To the questions:
1: Is this legal?
2: Would you suspect that Apple would be OK with giving the app 3 minutes of background over and over, thus leaving the process in the background for say a hour?
3: Would you count on this?
Thanks in advance!

Would you suspect that Apple would be OK with giving the app 3 minutes of background over and over, thus leaving the process in the background for say a hour?
No, Apple would not be OK with it, even if you could do it. They specified a 3 minute limit for a reason, to ensure that we don't have apps running in the background without the user's knowledge, consuming CPU cycles, memory, and draining the battery. (In fact, the "finite task" limit used to be 5 minutes, but several years ago Apple further restricted it to just 3 minutes.) Imagine a world where all app developers were routinely circumventing this 3 minute limit, our devices would have their batteries drained quickly and foreground apps would be less responsive and have less memory with which to operate.
Having said that, Apple has identified a very narrow set of operations that are acceptable to keep running in the background (VOIP, navigation apps, music apps, bluetooth operation, etc.), where the user has reasonable expectations about the battery and performance impact.
There are are also classes of tasks that employ some limited background capabilities (e.g. requesting time to complete some finite-length task, opportunistic periodic background fetch, significant change location services, giving the user a chance to respond to push or local notifications, etc.). The intent is to offer a meaningful balance between background capabilities while minimizing battery impact.
Bottom line, Apple otherwise discourages/curtails the use of indiscriminate background operation. In the App Store Guidelines, they explicitly say
2.16 Multitasking Apps may only use background services for their intended purposes: VoIP, audio playback, location, task completion, local notifications, etc.
...
4.5 Apps using background location services must provide a reason that clarifies the purpose of the use, using mechanisms described in the Human Interface Guidelines
Having said all of this, if you describe what precisely you need this background operation for, we might be able to describe which of the multitude of different background capabilities that Apple offers you could use to achieve the desired affect. All of these interfaces are designed to solve specific problems while balancing functionality with the scarce resources on our devices. But if it's something like "hey, I want to ping my server every five minutes", then no, Apple will frown upon that.
For more information, this is discussed in some detail in the Background Execution chapter of the App Programming Guide for iOS.

Related

Memory efficient way of using an NSTimer to update a MenuBar Mac application?

I am creating an application for Mac, in Objective C, which will run in the Menu-bar and do periodic Desktop operations (such as changing the wallpaper). I am creating the application so that it stays in the Menu bar at all times, allowing easy access to configuration options and other information. My main concern is how to schedule my app to run every X minutes to do the desktop operations.
The most common solution I have seen is using NSTimer, however, I am concerned that it will not be memory efficient (after reading the following page on Apple Developer docs. Using an NSTimer will prevent the laptop from going to sleep, and will need an always-running thread to check for when the NSTimer has elapsed. Is there a more memory-efficient way of using NSTimer to schedule these operations?
Alternately, is there a way to use LaunchD to initiate a call to my application (which is in the Menu bar) so that it can handle the event and do the desktop operations. I think that the second way is better, but am not sure if it is possible.
First, excellent instincts on keeping this low-impact. But you're probably over-worried in this particular case.
When they say "waking the system from an idle state" they don't mean system-level "sleep" where the screen goes black. They mean idle state. The CPU can take little mini-naps for fractions of a second when there isn't work that immediately needs to be done. This can dramatically reduce power requirements, even while the system is technically "awake."
The problem with having lots of timers flying around isn't so much their frequencies as their tolerances. Say one you have 10 timers with a 1 second frequency, but they're offset from each other by 100ms (just by chance of what time it was when they happened to start). That means the longest possible "gap" is 100ms. But if they were configured at 1 second with a 0.9 second tolerance (i.e. between 1s and 1.9s), then the system could schedule them all together, do a bunch of work, and spend most of the second idle. That's much better for power.
To be a good timer citizen, you should first set your timer at the interval you really want to do work. If it is common for your timer to fire, but all you do is check some condition and reschedule the timer, then you're wasting power. (Sounds like you already have this in hand.) And the second thing you should do is set a reasonable tolerance. The default is 0 which is a very small tolerance (it's not actually "0 tolerance," but it's very small compared to a minutes). For your kind of problem, I'd probably use a tolerance of at least 1s.
I highly recommend the Energy Best Practices talk from WWDC 2013. You may also be interested in the later Writing Energy Efficient Code sessions from 2014 and Achieving All-day Battery Life from 2015.
It is possible of course to do with with launchd, but it adds a lot of complexity, especially on installation. I don't recommend it for the problem you're describing.

operating system - context switches

I have been confused about the issue of context switches between processes, given round robin scheduler of certain time slice (which is what unix/windows both use in a basic sense).
So, suppose we have 200 processes running on a single core machine. If the scheduler is using even 1ms time slice, each process would get its share every 200ms, which is probably not the case (imagine a Java high-frequency app, I would not assume it gets scheduled every 200ms to serve requests). Having said that, what am I missing in the picture?
Furthermore, java and other languages allows to put the running thread to sleep for e.g. 100ms. Am I correct in saying that this does not cause context switch, and if so, how is this achieved?
So, suppose we have 200 processes running on a single core machine. If
the scheduler is using even 1ms time slice, each process would get its
share every 200ms, which is probably not the case (imagine a Java
high-frequency app, I would not assume it gets scheduled every 200ms
to serve requests). Having said that, what am I missing in the
picture?
No, you aren't missing anything. It's the same case in the case of non-pre-emptive systems. Those having pre-emptive rights(meaning high priority as compared to other processes) can easily swap the less useful process, up to an extent that a high-priority process would run 10 times(say/assume --- actual results are totally depending on the situation and implementation) than the lowest priority process till the former doesn't produce the condition of starvation of the least priority process.
Talking about the processes of similar priority, it totally depends on the Round-Robin Algorithm which you've mentioned, though which process would be picked first is again based on the implementation. And, Windows and Unix have same process scheduling algorithms. Windows and Unix does utilise Round-Robin, but, Linux task scheduler is called Completely Fair Scheduler (CFS).
Furthermore, java and other languages allows to put the running thread
to sleep for e.g. 100ms. Am I correct in saying that this does not
cause context switch, and if so, how is this achieved?
Programming languages and libraries implement "sleep" functionality with the aid of the kernel. Without kernel-level support, they'd have to busy-wait, spinning in a tight loop, until the requested sleep duration elapsed. This would wastefully consume the processor.
Talking about the threads which are caused to sleep(Thread.sleep(long millis)) generally the following is done in most of the systems :
Suspend execution of the process and mark it as not runnable.
Set a timer for the given wait time. Systems provide hardware timers that let the kernel register to receive an interrupt at a given point in the future.
When the timer hits, mark the process as runnable.
I hope you might be aware of threading models like one to one, many to one, and many to many. So, I am not getting into much detail, jut a reference for yourself.
It might appear to you as if it increases the overhead/complexity. But, that's how threads(user-threads created in JVM) are operated upon. And, then the selection is based upon those memory models which I mentioned above. Check this Quora question and answers to that one, and please go through the best answer given by Robert-Love.
For further reading, I'd suggest you to read from Scheduling Algorithms explanation on OSDev.org and Operating System Concepts book by Galvin, Gagne, Silberschatz.

iPad Kiosk Sleep Wake

I have an iPad kiosk that runs a single app, I would like to conserve power by having it sleep/lock or go to a low power state (dim the screen) either on regular scheduled times (outside of business hours) or when idle for specified period of time. The low power state on scheduled intervals will be good enough if it is simpler, as they are usually in pretty consistent use during the day.
Any tutorials out there that show how to accomplish this in Objective-C, or perhaps a few snippets to get me started?
The kiosks physically prohibit use of any of the buttons. I looked into iOS 6 Guided Access, but I don't see how a user could unlock/wake the screen without access to the buttons. Another solution could be Kiosk Pro Plus - but $40 bucks a pop just for sleeping doesn't seem worth it, I'd like to program it myself if feasible.
MokiTouch is a free alternative to KioskPro and has the sleep feature. You can pay to add remote management, but that's optional.
MokiTouch.com for more info.

Do other apps affect my app's performance on iOS?

Given the multitasking function of iOS, will other applications that are currently sleeping affect my app (which is currently active) performance or memory consumption?
Absolutely. Any application that is running in the background (within the various parameters for when that's legal) will impact CPU availability. Apple apps can run in many more situations than 3rdparty apps, and they also will compete with you. I've particularly had trouble with Mail.app in the past.
Memory performance is a bit trickier, but yes, other applications are in memory at the same time and you can definitely generate memory warnings sooner with other applications in memory than you would otherwise. In principle, you should be able to get as much memory eventually as you would without other apps running, but that's not completely true. In particular, don't forget that Apple's apps don't always follow the same rules as 3rdparty apps, and if they're eating a lot of memory, they may or may not be killed.
The other performance consideration is network bandwidth, and this is most certainly a way that background apps may compete with you. I don't believe Apple is applying any bandwidth limiting on background apps, and downloading large files is a prime background activity. (There is some discussion that AppStore may decline apps that hit the network too hard while in the background, but I'm not aware of an official position on this. In any case, it it certainly legal to use some bandwidth in the background, and that's bandwidth not available to the foreground app.)
No they won't.
When the active app needs more memory being used by background apps, it automatically kills them off so the active app can use the resources.

Power Management in Symbian

Are there any "best practices" for writing a power-efficient background application in Symbian?
Specifically, is there any way (i.e. API) for a Symbian app to hint the OS regarding its current state in order to reduce battery consumption?
In Android, for instance, there is the notion of Wake Locks, which prevents the device from going into standby mode - Is there anything similar in Symbian?
EDIT:
Are there any implications when running code as a separate thread with the Open-C library, and not as "native" Symbian C++, using Active Objects etc.? (the Open-C code is blocking on IO most of the time).
You can check user (in-)activity with a RTimer::Inactivity() method. This way is described in Forum Nokia Wiki page. There it's also described how you can reset inactivity timer.
You can check whether device screen is turned on or off using HAL API. See classes HAL and HALData. You may use such a call:
TInt displayState;
HAL::Get(HALData::EDisplayState, displayState);
And the displayState will hold either 0 if display is turned off or 1 in other case.
With these APIs you will know whether user is active now, so you'll be able to change behavior of your background service to reduce its power consumption.
You can also use Nokia Energy Profiler application to record power consumption of handset, with different power saving options of your background service. Also please refer to Nokia's document describing best practices to save power of device. This document is quite straightforward, but useful nonetheless.
Hope this helps.
EDIT: About separate thread and Open C. As far as I know, Open C is just a plugin and deep down all the implementations are still "native Symbian". So, as far as you avoid periodic polling of some resource and just use usual blocking IO, your code is quite same economical on power as standard Symbian Active Objects techniques (which use Symbian-specific semaphores to block threads).
I have not come across anything special in Symbain to keep the device out of stand-by mode. Basically the "best practices" would be the same as all mobile devices:
Don't loop waiting for things, always use whatever signaling services avaialble on the platform, for Symbain ActiveObjects / User::WaitForXxx
Limit the number of background threads (currently all mobile devices are still only 1 CPU...)
Don't hang onto system services, close them ASAP (this is normally my main battery drain in my mobile applications, sometimes trying to find which system service causes the most battery drain can be a real pain, WinMo is very bad for this).
For me, I find that it mostly comes down to a tradeoff between battery life and performance / responsiveness for the application. Unfortunately power that be always seem to side with the performance / responsiveness side and damn the battery drain.....
Give your application low priority (see RProcess and RThread classes). Your approach will really depend on what your background application does. These things consume most battery: radio (GSM/3G/WIFI/BlueTooth), screen backlight, file accesses.
Symbian OS will always try to put your application to sleep, you don't need to tell it to do this. Just make sure your approach gives it the opportunity to put it to sleep.
Power management is an very most important issue while developing application.
In Symbian it depends on what you are using to run background activities .
Whether you are using Thread or ActiveX control.
For Eg. you are developing application browser that you want the browser to download something then that downloading activity should go in background and able activity starts and when to show progress and when it finishes it should again come to fore end.
It depends on how you are managing thread if you are using thread. You can do like which thread to pause when the long time taking activity starts and when to resume when background activity has finishes execution..
In fact this is the very good topic u have come across
There used to be an inactivity timer which could be reset by the application. This would prevent the screen from going into any screen saver mode.
If you use the various asynchronous function in Symbian, your app will run when appropriate.
One of these methods should work depending on your needs. If you describe what you want to achieve in more detail it would be easier to help you.