I had a similar problem, there's no straight forward solution in the core for this as I see. There is a semaphore table where cron adds and removes a record when it starts and finishes, but that doesn't tell which thread/session is the cron run. I've solved my problem with the following session test:
/**
* Tries to determinate if current session is a cron run.
*
* @return bool
* Returns true, the session belongs to a cron run, otherwise false.
*/
function _MODULE_is_cron_run(): bool {
$route = \Drupal::routeMatch();
// Check if the cron is executed from the interface OR
// if it was executed from the CLI with drush cron.
return (
$route->getRouteName() === 'system.run_cron' ||
PHP_SAPI === 'cli' && function_exists('drush_main') && in_array('cron', $_SERVER['argv'])
);
}
I think the rest is straight forward, you call this method from whenever you want and it will tell you if it's cron or not. Of course, if you have another solution for calling Drupal cron, then you may need to adapt this to match your requirement.
If you also need to check in batch process, then you need the following:
/**
* Tries to determinate if current session is a cron run.
*
* @return bool
* Returns true, the session belongs to a cron run, otherwise false.
*/
function _MODULE_is_cron_run(): bool {
$route = \Drupal::routeMatch();
// Check if the cron is executed from the interface OR
// if it was executed from the CLI with drush cron.
return (
$route->getRouteName() === 'system.run_cron' ||
PHP_SAPI === 'cli' && function_exists('drush_main') && (in_array('cron', $_SERVER['argv']) || in_array('batch-process', $_SERVER['argv']))
);
}
hook_entity_update? I currently have a Drupal 8 site that is successfully detecting scheduled updates on nodes being executed by cron, so that should work for you. - mpriscella