> For the complete documentation index, see [llms.txt](https://support.morozovpimnev.ru/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://support.morozovpimnev.ru/kroner/kod-handler.md).

# Код Handler

Задача должна наследоваться от `ASMP_Cron_Handler`.

{% code lineNumbers="true" fullWidth="true" %}

```php
<?php

class ASMP_Cron_Handler1 extends ASMP_Cron_Handler
{
    public function execute()
	{
	    $oShop = Core_Entity::factory('Shop', 1);
	    
	    $oCore_QueryBuilder_Select = Core_QueryBuilder::select('shop_items.id')
	        ->from('shop_items')
	        ->where('shop_items.shop_id', '=', $oShop->id)
	        ->open()
                ->where('shop_items.image_large', 'IS', NULL)
                ->setOr()
                ->where('shop_items.image_large', '=', '')
            ->close();
            
        $iFrom = 0;
        $step = 5000;
        
         do {
            $oCore_QueryBuilder_Select->offset($iFrom)->limit($step);
            
            $aRows = $oCore_QueryBuilder_Select->execute()->asAssoc()->result(FALSE);
            
            foreach ($aRows as $row)
            {
                $aIDs[] = $row['id'];
            }
            
            $iFrom += $step;
        
            $iCount = count($aRows);
        }
        while ($iCount);
        
        $this->_total = count($aIDs);
        
        if($this->_total)
        {
            $siteUrl = $this->_getSiteUrl();

            foreach ($aIDs as $entity_id)
            {
                $oShop_Item = Core_Entity::factory('Shop_Item', (int) $entity_id);

                $message = sprintf('%1$s/admin/shop/item/index.php?hostcms[action]=edit&shop_id=%2$d1&shop_group_id=%3$d&hostcms[checked][1][%4$d]=1', $siteUrl, $oShop_Item->shop_id, $oShop_Item->shop_group_id, $oShop_Item->id);

                $this->addLog($message, -1);
            }
        }

	    return TRUE;
	}
}
```

{% endcode %}

## Поддерживаемые методы в execute()

{% code overflow="wrap" fullWidth="true" %}

```php
// задать кол-во элементов, попавших под выборку или с которыми происходил какой-то процесс, выводится в отчете
$this->_total = 450;
$this->_total++;

/**
* добавить запись в лог/отчет
* поддерживаемые статусы: MESSAGE (по умолчанию), SUCCESS, ERROR
*/
$message = 'какой-то мой текст';
$this->addLog($message);

$message = 'ошибка!';
$this->addLog($message, 'ERROR');

// получить ссылку на сайт, например для подстановки ссылки на элемент
$siteUrl = $this->_getSiteUrl(); // https://mysite.ru

// объект ASMP_Cron текущей задачи, от неё можно получить, например, ID сайта
$this->_ASMP_Cron->site_id

// Если вдруг хотите запретить отправку отчета на email в какой-то момент
$this->_report_email = FALSE;
```

{% endcode %}

## heartbeat - механизм продления lock во время выполнения долгой задачи

TTL на одну задачу выставлен 60 минут. Если задача выполняется дольше, то её lock нужно продлевать. Иначе она запустится снова параллельно текущей. Для этого в модуле реализован механизм heartbeat.

{% code fullWidth="true" %}

```php
// Например, если у вас долгий парсер, то можно после каждого 50-го элемента запускать _heartbeat()
public function execute()
{
    $items = $this->getItems();

    foreach ($items as $i => $item)
    {
        $this->process($item);
        
        // каждые 50 элементов продлеваем lock
        if ($i % 50 === 0) {
            $this->_heartbeat();
        }
    }
}

// Или просто каждые 5 минут продлевать его
public function execute()
{
    $items = $this->getItems();

    foreach ($items as $i => $item)
    {
        $this->process($item);
        
        // каждые 5 минут продлеваем lock
        // функция сама считает сколько прошло времени
        $this->_heartbeatIfNeeded();
    }
}
```

{% endcode %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://support.morozovpimnev.ru/kroner/kod-handler.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
