title: Jenkins How to find if a given slave is running a Job
body: <p>I have this unique requirement to check if the given node is running a job or not. I am thinking of using groovy as it looks easiest option.</p>
  
  <p>I have found this answer to be useful.</p>
  
  <p><a href="https://stackoverflow.com/questions/23761479/how-can-i-check-via-a-script-or-a-plugin-in-jenkins-whether-a-slave-is-online-be">How can I check via a script or a plugin in Jenkins whether a slave is online before starting a build from another project on it</a></p>
  
  <p>It allows me to find if the slave is online or not. Next step for me is to check if it is running a job. </p>
  
  <p>I was considering using the <a href="http://javadoc.jenkins-ci.org/hudson/slaves/SlaveComputer.html" rel="noreferrer">API</a> function <a href="http://javadoc.jenkins-ci.org/hudson/slaves/SlaveComputer.html#setAcceptingTasks%28boolean%29" rel="noreferrer">setAcceptingTasks(false)</a> to mark slave as running a Job so that when next time I query using <a href="http://javadoc.jenkins-ci.org/hudson/slaves/SlaveComputer.html#isAcceptingTasks%28%29" rel="noreferrer">isAcceptingTasks()</a>, I get false and hence do not launch job on that slave.</p>
  
  <p>But I would rather have the slave mark itself. </p>
  
  <p><a href="http://javadoc.jenkins-ci.org/hudson/slaves/SlaveComputer.html#taskAccepted%28hudson.model.Executor,%20hudson.model.Queue.Task%29" rel="noreferrer">taskAccepted()</a> and <a href="http://javadoc.jenkins-ci.org/hudson/slaves/SlaveComputer.html#taskCompleted%28hudson.model.Executor,%20hudson.model.Queue.Task,%20long%29" rel="noreferrer">taskCompleted()</a> come to mind.  <strike>I can call the setAcceptingTasks to false once task is accepted and on completion of tasks set isAcceptingTasks to true once again.  </p>
  
  <p>But I am not sure of the arguments these functions take e.g executor and task. And where do these function calls fit in a groovy script.</strike></p>
  
  <p>I am not sure if my assumption of task is equivalent to a job is true or not.</p>
  
  <p>This is what I have got till now:</p>
  
  <pre><code>import hudson.model.*
  def requiredNodes = ['Slave1', 'Slave2', 'Slave3'];
  def status = 0;
  for (node in requiredNodes) 
  {
        println "Searching for $node";
        slave = Hudson.instance.slaves.find({it.name == node});
        if (slave != null)
         {
          computer = slave.getComputer();
          if (computer.isOffline())
           {
             println "Error! $node is offline.";
             status = 1;
           }
           else 
           {
             println "OK: $node is online";
             if(computer.isAcceptingTasks())
             {
                //Launch job
             }
           }
         }
         else 
         {
           println "Slave $node not found!";
           status = 1;
         }
  }
  status;
  </code></pre>
  
  <p>EDIT: Number of executors on each slave is 1.</p>