Is it possible to determine if a script is running within a task? I have a chunk of PHP code which should not be run if the script is being executed from a task.

We already have these methods, which are similar to what I'm looking for:


craft()-&gt;isConsole() - Whether the script is running in the console.
craft()-&gt;request-&gt;isCpRequest() - Whether the script is running in the CP.


Is there a way to tell if the script is running inside of a task?

(Since my research has turned up nothing so far, I opened a related feature request...)
TasksService-&gt;getRunningTask() will tell you if a task is currently running. However, it doesn't tell you whether a particular chunk of code is being executed by that Task or by some other function.

The most straightforward solution I can think of would be to write yourself a little helper method to check whether the call stack includes a Task class:

static function inTask()
{
   foreach(debug_backtrace() as $caller)
   {
      if (substr($caller['file'], -8) === 'Task.php') return true;
   }
   return false;
}


Add that to your plugin class, and then you can call it anywhere you need:

if (MyPlugin::inTask()) ...