Waiting for code to execute before moving on to next command

I'm using NMSSH in order to connect to a server and then grab data off that server. However, connecting to the server, performing commands, and retrieving the data all take time to complete. Previously, I was using

sleep()
commands in order to allow the program to pause and let those commands finish running but if I don't specify the exact amount of time to sleep the data may not fully finish downloading (since the data varies in size its hard to determine the correct amount of sleep). So after doing some research it seemed that Dispatch Groups and Async operations were the correct way to go. I implemented these as follows:


let queue = DispatchQueue(label: "myqueue", attributes: .concurrent, target: .main)
let group = DispatchGroup()

let myfirstconnection: SSH = SSH()
myfirstconnection.hostname = "@hostname"
myfirstconnection.username = "user"
myfirstconnection.password = "password"

queue.async(group: group) {
     myfirstconnection.connectToServer()
     print("1")
}
group.wait()

queue.async(group: group) {
     myfirstconnection.performCommand()
     print("2")
}
group.wait()

queue.async(group: group) {
     myfirstconnection.retrieveData()
     print("3")
}
group.wait()

queue.async(group: group) {
     myfirstconnection.endSession()
     print("4")
}
group.wait()


But, this does not seem to be working correctly because all the commands still run at the same time. Essentially I need each block above to run, then wait until completed before moving to the next block. Any help would be appreciated, thanks.

Replies

It’s hard to answer this question without knowing more about the concurrency model exposed by NMSSH. I had a quick look at the docs but there’s no obvious correlation between the code example you posted and the example in the docs.

It seems that NMSSH is a fully synchronous API, in which case you would just execute these command one after another with no intervening dispatch code. Something like this:

queue.async {
    myfirstconnection.connectToServer()
    myfirstconnection.performCommand()
    myfirstconnection.retrieveData()
    myfirstconnection.endSession()
}

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"