I am using dispatch queue to manage a series of background tasks (download multiple files on user's demand and without waiting in UI) and so far it worked great. More over I need to persistent the unfinished tasks, so for example if there is no network reach-ability, or the app crashed, or phone's battery dead, next time when the app run, all tasks will resume automatically.
I am planning to make each task block save the task in a core data context, and remove it once the task is finished, and also I will need to perform a check when app start to see if there is any task to do.
What's the best practice of creating this sort of application? Is there any sample, tutorial or library that I can reuse?
Here are how operation queues are different from dispatch queues: In operation queues, you can set priority for your operations and also you can add dependencies to the operations which means you can define that some operation execute only after the completion of other operations.
Dispatch queues are FIFO queues to which your application can submit tasks in the form of block objects. Dispatch queues execute tasks either serially or concurrently. Work submitted to dispatch queues executes on a pool of threads managed by the system.
Grand Central Dispatch (GCD) is a low-level API for managing concurrent operations. It can help improve your app's responsiveness by deferring computationally expensive tasks to the background. It's an easier concurrency model to work with than locks and threads.
Generally queues are used as a way to 'connect' producers (of data) & consumers (of data). A thread pool is a pool of threads that do some sort of processing. A thread pool will normally have some sort of thread-safe queue (refer message queue) attached to allow you to queue up jobs to be done.
Your technique should pretty much work. Design the class that manages your background tasks to "blindly" execute any tasks that is given to it.
Submit tasks to this class from your various view controllers. The submit method should look like
-(void) submitTask:(MyTask*) task {
task.completionHandler = ^{ [self.runningTasks removeObject:task];}
[self.taskQueue addOperation: task];
}
I'm assuming that MyTask is a subclass of NSOperation and taskQueue is a NSOperationQueue. The runningTasks is simply an NSMutableArray which is serialized to disk (either to CoreData or whatever format you like) when you receive a UIApplicationDidEnterBackgroundNotification.
You can implement a similar design with GCD as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With