How to run two tasks independently - objective-c

I am building one application on Mac OS X (10.6). In this application, I have one screen where user will provide input and that will be saved as a plist in local folder. This plist file needs to be trasferred to server using HTTP POST service. There should be check for server connectivity and if connections fails the files will be saved in local folder. With certain time duration, again the server connection will be checked and if found, then send all the files store in local folder one by one.
Basically, The GUI application will run continously to get input from user and in another thread there should be check for server connectivity and sending the files.
So my question is what might be the good approach to solve the problem and if any one can send some sample code, it would be great to me.
Thanks,
Barun

There are several approaches to threading in Objective-C! The easiest strategy is NSOperationQueue. Override NSOperation to handle your HTTP request, optionally set a completion block if you need to be notified when it's done, add an instance of it to an NSOperationQueue object and you're good to go. Set up an NSTimer to reschedule the upload if it fails the first time. You can use NSURLConnection to handle the web stuff. Note that NSURLConnection can make connections asynchronously or blocking. Since your NSOperation subclass runs in a separate thread already, you probably want to use the blocking method (if you don't you have to create a concurrent NSOperation subclass, which is a lot more work).
You can also use Grand Central Dispatch's API, detach a new thread to methods you specify, or use plain old c (I wouldn't recommend the last two but it's good to mention them). As a bonus, NSOperationQueue and Grand Central Dispatch both know "what's right" when you have multiple operations running at once, and will scale the number of threads to fit the number of core's in the user's computer to obtain the best performance.
Check the docs for NSOperationQueue, NSOperation, and NSURLConnection. The guides and example projects will have all the source code you need to get you started in the right direction.

Related

Async WCF and Protocol Behaviors

FYI: This will be my first real foray into Async/Await; for too long I've been settling for the familiar territory of BackgroundWorker. It's time to move on.
I wish to build a WCF service, self-hosted in a Windows service running on a remote machine in the same LAN, that does this:
Accepts a request for a single .ZIP archive
Creates the archive and packages several files
Returns the archive as its response to the request
I have to support archives as large as 10GB. Needless to say, this scenario isn't covered by basic WCF designs; we must take additional steps to meet the requirement. We must eliminate timeouts while the archive is building and memory errors while it's being sent. Both of these occur under basic WCF designs, depending on the size of the file returned.
My plan is to proceed using task-based asynchronous WCF calls and streaming mode.
I have two concerns:
Is this the proper approach to the problem?
Microsoft has done a nice job at abstracting all of this, but what of the underlying protocols? What goes on 'under the hood?' Does the server keep the connection alive while the archive is building (could be several minutes) or instead does it close the connection and initiate a new one once the operation is complete, thereby requiring me to properly route the request through the client machine firewall?
For #2, clearly I'm hoping for the former (keep-alive). But after some searching I'm not easily finding an answer. Perhaps you know.
You need streaming for big payloads. That is the right approach. This has nothing at all to do with asynchronous IO. The two are independent. The client cannot even tell that the server is async internally.
I'll add my standard answers for whether to use async IO or not:
https://stackoverflow.com/a/25087273/122718 Why does the EF 6 tutorial use asychronous calls?
https://stackoverflow.com/a/12796711/122718 Should we switch to use async I/O by default?
Each request runs over a single connection that is kept alive. This goes for both streaming big amounts of data as well as big initial delays. Not sure why you are concerned about routing. Does your router kill such connections? That's a problem.
Regarding keep alive, there is nothing going over the wire to do that. TCP sessions can stay open indefinitely without any kind of wire traffic.

How can I share an object between a Rails instance and a Sidekiq instance

I have a listener (using the Listen gem) object that I'm adding to a constant within an initializer:
LISTENER = Listen.to(REPORT, ERROR, SENT) do |modified, added, removed|
listener.ignore! /\.swp/
listener.ignore /\.DS_Store/
Communicator.notify(added)
end
I put a little admin interface around this functionality, and I display the status of the listener in the view.
In my deployment, I have a Utility instance where all my background jobs run. I may have 1 or many app servers spinning at one time, so I only want this listener to listen on the Utility instance. Sidekiq is my background processor. Therefore, in my admin interface I enlist a simple Sidekiq worker to spin up this listener.
When I obtain the status of the listener, it says it isn't running. But the process is there. This of course is because the App server is attempting to get the listener status from the constant on the application server!
How can I get the status of the object on the Sidekiq server?
Rails 4.2 has implemented GlobalID and here is a good blog post outlining ActiveJob and it covers using GlobalID. (You can parse live object! OMG section)
I know this is an old post but I just came across it and thought this answer might help someone.
Sidekiq and Application Servers do no share memory. Even the Application server instances do not share memory. You will have to use database to share the information between sidekiq and your application.
Add the status of the listener to the database from your sidekiq process. Read the database value in your application server request.
Seems that you want to use Distributed Ruby: http://www.ruby-doc.org/stdlib-2.1.0/libdoc/drb/rdoc/DRb.html.
dRuby allows methods to be called in one Ruby process upon a Ruby object located in another Ruby process, even on another machine. References to objects can be passed between processes. Method arguments and return values are dumped and loaded in marshalled format. All of this is done transparently to both the caller of the remote method and the object that it is called upon.

How to keep track of MailCore operations

I'm trying to build an OS X mail client using MailCore2, and I need to know what current operations are currently running, and in what state they are — think Mail.app activity monitor window.
I've some things that I could use in the API : The MCOIMAPSession object has a operationQueueRunningChangeBlock property, but it only tells me when the session changes states (running => not running) but that is insufficient.
Right now I think I'll have to subclass/wrap those to do what I want.
MailCore does not provide an API to track running operations, nor should we, because that is your job. A typical pattern to implement this would be to either subclass the operation classes to tag each one with some kind of activity object, or aggregate activities in a separate queue and push and pop as operations are enqueued and dequeued respectively. The completion blocks of each request in the Objective-C interface should provide enough of the state of each operation for you, and some specific kinds of operations even include progress blocks/hooks.

Desing pattern for background working app

I have created a web-service app and i want to populate my view controllers according to the response i fetch(via GET) in main thread. But i want to create a scheduled timer which will go and control my server, if there becomes any difference(let's say if the count of an array has changed) i will create a local notification. As far as i read from here and some google results, i cant run my app in background more then ten minutes expect from some special situations(Audio, Vo-IP, GPS).. But i need to control the server at least one per minute.. Can anyone offer some idea-or link please?
EDIT
I will not sell the app in store, just for a local area network. Let's say, from the server i will send some text messages to the users and if a new message comes, the count of messages array will increment, in this situation i will create a notification. I need to keep this 'controlling' routing alive forever, whether in foreground or background. Does GCD give such a solution do anyone have any idea?
Just simply play a mute audio file in loop in the background, OR, ping the user's location in the background. Yes, that will drain the battery a bit, but it's a simple hack for in-home applications. Just remember to enable the background types in your Info.plist!
Note: "[...] I fetch (via GET) in main thread." This is not a good approach. You should never fetch any network resources on the main thread. Why? Because your GUI, which is maintained by the main thread, will become unresponsive whenever a fetch isn't instantaneous. Any lag spike on the network results in a less than desirable user experience.
Answer: Aside from the listed special situations, you can't run background apps. The way I see it:
Don't put the app in the background. (crappy solution)
Try putting another "entity" between the app and the "server". I don't know why you "need to control the server at least one per minute" but perhaps you can delegate this "control" to another process outside the device?
.
iOS app -> some form of proxy server -> server which requires
"babysitting" every minute.

Using Appkit Framework in Launch Daemon

I want to use NSWorkspace to check if application is launched or closed.
But the process is Launch Daemon and Apple documentation says its not thread safe.
However, the part of code that makes use of Workspace will not be executed at start up or login time. It will be executed after some commands received from other application via BSD communication and process is background process without UI?
Is it safe to use Appkit framework in this situation? Only NSWorkspace API and no other? Alternate solution is Polling? What is your suggestion?
Generally you can use any code that isn't thread safe, as long as you are only doing one operation of whatever the unthreadafe operation is at any given time. I would go ahead and try it, and just be aware that whatever you are doing you can't do concurrently, if you absolutely need to do something concurrently you can try throwing a couple of #synchronized blocks around the code, either in callbacks of a long running background process, or delegate calls.