Question

This is what I want to do and I use JSch for it:

  • copy file A, from server S1 to server S2
  • when this is done, do some logic (e.g. send an email about task completion)

What I don't know:

  • Is JSch doing the write in a new thread or not? What makes it confusing is the fact that ChannelSftp implements Runnable, thus is potentially run as a separate thread.

If it does run it in a separate thread, then I can't add my code after the put method, but need to potentially use the SftpProgressMonitor instead (maybe?!).

Unfortunately I couldn't find anything in their documentation about how the call to put or any other methods would be run - synchronous or asynchronous.

Was it helpful?

Solution

What I did was monitor the exit status of the command executed in a loop, whenever the status is -1 (means it is still running) then I sleep the current thread, for safety it's a good idea to break when holding reach a time limit, but that's up to you.

    final JSch jsch = new JSch();
    final Session sessionJSH = jsch.getSession(user, host, 22);
    sessionJSH.setPassword(pwd);
    final Hashtable configJSH = new Hashtable();
    configJSH.put("StrictHostKeyChecking", "no");
    sessionJSH.setConfig(configJSH);
    sessionJSH.connect();
    final Channel channel = sessionJSH.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    channel.connect(0);
    // we'll hold it until 30 minutes = 30m*60s*1000ms/300ms = 6000 times
    int i = 0;
    while (channel.getExitStatus() == -1 && i < 6000) {
        log.debug("Exit status" + channel.getExitStatus());
        Thread.sleep(300);
        i++;
    }
    log.info("Exit status" + channel.getExitStatus());
    channel.disconnect();
    sessionJSH.disconnect();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top