[Solved] Cron is running but not saving entity

Jean da Silva Asks: Cron is running but not saving entity
I am trying to create a simple hook_cron to connect with an external API, return some data and update some fields in some entities. I’m creating like this to understand better how cron works, so I will upgrade it later to a queue.

The problem is that the cron is running, but even without errors the entity is not saving or updating. If I copy the code and try to execute it with a route (not using cron), it works as intended. I really don’t know what is the problem with it.

I thank you for your help.

The code below:

function correios_web_service_cron()
    $trackingService = Drupal::service('correios_web_service.tracking');
    $eventService = Drupal::service('correios_web_service.event');

    $error = null;

    try {
        $order_ids = Drupal::entityQuery('commerce_order')
            ->condition('type', 'campaign') //! Ver se terá que mudar o tipo
            ->condition('state', $eventService->getStatusByAlias('entregue')['description'], '<>')
            ->condition('state', $eventService->getStatusByAlias('avaliado')['description'], '<>')
            ->condition('state', $eventService->getStatusByAlias('cancelado')['description'], '<>')
            ->condition('field_tracking_code', NULL, '<>')

        $Orders = Drupal::entityTypeManager()->getStorage('commerce_order')->loadMultiple($order_ids);
    catch (Throwable $e) {
        $error = $e->getMessage();

    if (empty($error) && !empty($Orders)) {
        foreach ($Orders as $Order) {
            $tracking_code = $Order->get('field_tracking_code')->value;

            try {
                $response = $trackingService->trackObjectFormatted($tracking_code);

                $Order->set('state', $response['description']);
                $Order->set('field_tracking_event_code', $response['event_code']);
                $Order->set('field_tracking_event_message', $response['event_message']);
                $Order->set('field_tracking_delivery_date', $response['delivery_date']);

            catch (Throwable $e) {
    if (!empty($error)) {

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.