title: SQL Agent Job: Determine how long it has been running
body: <p><strong>The Scenario</strong></p>
  
  <p>There are certain SQL Agent Jobs that are scheduled to run every few minutes throughout the day.</p>
  
  <p>There are legitimate times when it will miss its next schedule because it's still running from the previous schedule.</p>
  
  <p>Every once and a while, a job might 'hang'. This doesn't produce a failure (since the job hasn't stopped yet). When this happens, the job can be manually stopped and works fine the next time it runs. It's designed to pick back up where it left off.</p>
  
  <p><strong>What's the most efficient way...?</strong></p>
  
  <p>I'd like a way to determine how long (in seconds) a SQL Agent Job named 'JobX' is currently running. If it isn't currently running, we can just return zero.</p>
  
  <p>This way, I can stop the job if it has been running for an amount of time beyond a certain threshold.</p>
  
  <p>I assume that a combination of xp_sqlagent_enum_jobs and sysjobhistory could be used, but I'm curious if there are better solutions out there... and can hopefully benefit from the obstacles the rest of you have already run into and worked around.</p>