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()->isConsole() - Whether the script is running in the console.
  • craft()->request->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->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()) ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.