What is the best way to determine if a script is being run by cron in Magento2?
-
16-04-2021 - |
Question
I need a piece of code to execute differently if it's being run by cron, what is the best way to check programmatically that cron is the execution source?
I know that it can be done by checking for website or session being unavailable, but I'm concerned these seem a bit hacky. I'm wondering if there's some clean isRunningFromCron kind of function that abstracts this to dependency-inject, or if the aforementioned hacks would be robust enough that I'm being over-cautious.
Thanks!
EDIT: It may actually not be possible to use the current store ID check in my circumstance, as the script is otherwise being run from adminhtml, which I think would also have a store_id of 0
Solution
Well basically you should be able to use the area code for your needs. Take the example of the vendor/dotmailer/dotmailer-magento2-extension/Console/Command/TaskRunnerCommand.php
class which uses Magento\Framework\App\State
to handle the current area:
try {
$this->state->setAreaCode(Area::AREA_CRONTAB);
} catch (LocalizedException $e) {
if ($this->state->getAreaCode() != Area::AREA_CRONTAB) {
$output->writeln(__(
sprintf('Warning: command running in an unexpected state (%s)', $this->state->getAreaCode())
)->getText());
}
}
So you could set the area as crontab for the part that is meant for your cron to execute.
More on Magento areas here: https://devdocs.magento.com/guides/v2.4/architecture/archi_perspectives/components/modules/mod_and_areas.html#magento-area-types
Good luck!