0
votes

I need detect action: When node will published by CRON in Drupal 8.

Scheduling options

For example: user creating new article in Drupal and setting scheduling option(publish on) on the next day, when Drupal will publish article I must detect this event and send request to another server.

hook_cron - not helped.

hook_entity_update - in this hook, I can't detect updating by CRON. In this case I mean: How can I detect who update node CRON or User?

I need to find the update of the node only by CRON.

Maybe Drupal 8 has other actins or properties for detect: updating node by CRON.

1
Can you share your implementation of 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
In this case I mean: How can I detect who update node CRON or User? - Alexander Pyrkin

1 Answers

0
votes

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']))
  );
}