1
0
mirror of synced 2025-02-21 01:13:13 +03:00

Add functionality for changing the time interval for cron tasks

This commit is contained in:
Dima Uryvskiy 2022-07-05 18:24:04 +03:00 committed by GitHub
parent 2b17ec6a1c
commit b8c1cd9ec8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 155 additions and 23 deletions

53
doc/1.Setup/Cron tasks.md Normal file
View File

@ -0,0 +1,53 @@
### Настройки cron задач
В версии 4.4.5 добавлен функционал для изменения интервалов времени выполнения cron задач.
Для изменения интервала времени необходимо с помощью фильтра **retailcrm_add_cron_interval** добавить пользовательский интервал. Затем изменить интервал для cron задач с помощью фильтра **retailcrm_cron_schedules**.
Кастомизацию необходимо добавить на сервере в директорию wp-content -> mu-plugins -> mu-simla.php. После добавления кастомизации в настройках модуля необходимо очистить старые cron задачи.
Перейдите в настройки, откройте "Отладочная информация" и нажмите на кнопку "Очистить cron задачи", появится окно с сообщением об успешной очистке, интервалы будут применены.
Если необходимо вернуть стандартные интервалы, то удаляем кастомизацию и в настройках так же очищаем старые cron задачи.
**Интервалы по умолчанию:**
```php
[
'icml' => 'three_hours',
'history' => 'five_minutes',
'inventories' => 'fiveteen_minutes',
]
```
> Важно! При использовании фильтра **retailcrm_cron_schedules**, можно использовать ключи: 'icml', 'history', 'inventories'.
**Фильтры:**
> retailcrm_add_cron_interval - позволяет добавить пользовательский интервал времени.
> retailcrm_cron_schedules - позволяет изменить интервал времени для cron задач.
**Пример использования:**
```php
<?php
add_filter('retailcrm_add_cron_interval', 'add_cron_interval');
function add_cron_interval($schedules)
{
return ['two_minutes' => [
'interval' => 120, // seconds
'display' => __('Every 2 minutes')
]
];
}
add_filter('retailcrm_cron_schedules', 'change_cron_tasks');
function change_cron_tasks($cronTasks)
{
$cronTasks['history'] = 'two_minutes';
return $cronTasks;
}
```

View File

@ -326,4 +326,16 @@ msgid "Short description"
msgstr "Descripción corta"
msgid "In the catalog, you can use a full or short description of the product"
msgstr "En el catálogo, puedes utilizar una descripción del producto corta o completa"
msgstr "En el catálogo, puedes utilizar una descripción del producto corta o completa"
msgid "If you change the time interval, need to clear the old cron tasks"
msgstr "Si cambias el Intervalo de Tiempo tienes que limpiar los cron tareas antiguos"
msgid "Clear cron tasks"
msgstr "Borrar tareas cron"
msgid "Clear"
msgstr "Borrar"
msgid "Cron tasks cleared"
msgstr "Trabajos cron borrados"

View File

@ -337,3 +337,14 @@ msgstr "Краткое описание"
msgid "In the catalog, you can use a full or short description of the product"
msgstr "В каталоге можно использовать полное или краткое описание товара"
msgid "If you change the time interval, need to clear the old cron tasks"
msgstr "Если вы изменили временной интервал, необходимо очистить старые cron задачи"
msgid "Clear cron tasks"
msgstr "Очистить cron задачи"
msgid "Clear"
msgstr "Очистить"
msgid "Cron tasks cleared"
msgstr "Cron задачи очищены"

View File

@ -1,7 +1,3 @@
.retail-cron-info {
padding: 5px 30px !important;
}
.retail-cron-info-title {
font-weight: bold;
}

View File

@ -1 +1 @@
.retail-cron-info{padding:5px 30px!important}.retail-cron-info-title{font-weight:700}
.retail-cron-info-title{font-weight:700}

View File

@ -2,14 +2,20 @@ jQuery(function () {
function RetailcrmCronInfo()
{
this.title = jQuery('.debug_info_options').get(0)
this.submitButton = jQuery('button[id="clear_cron_tasks"]').get(0);
if (typeof this.title === 'undefined') {
return false;
}
this.history = 0;
if (typeof this.submitButton === 'undefined') {
return false;
}
this.icml = 0;
this.history = 0;
this.inventories = 0;
this.messageSuccessful = '';
let _this = this;
@ -24,14 +30,19 @@ jQuery(function () {
_this.history = response.history;
_this.icml = response.icml;
_this.inventories = response.inventories;
_this.messageSuccessful = response.translate.tr_successful;
_this.displayInfoAboutCron(
response.translate.tr_td_cron,
response.translate.tr_td_icml,
response.translate.tr_td_history,
response.translate.tr_td_inventories
response.translate.tr_td_inventories,
);
})
this.clearCronTasks = this.clearCronTasks.bind(this);
jQuery(this.submitButton).click(this.clearCronTasks);
}
RetailcrmCronInfo.prototype.displayInfoAboutCron = function (cron, icml, history, inventories) {
@ -40,11 +51,23 @@ jQuery(function () {
this.infoTable = jQuery('tbody[class="retail-debug-info"]').get(0);
jQuery(this.infoTable).append("<tr><td class='retail-cron-info-title'>" + cron + " : " + "</td></tr>");
jQuery(this.infoTable).append("<tr><td class='retail-cron-info'>" + icml + " : " + this.icml + "</td></tr>");
jQuery(this.infoTable).append("<tr><td class='retail-cron-info'>" + history + " : " + this.history + "</td></tr>");
jQuery(this.infoTable).append("<tr><td class='retail-cron-info'>" + inventories + " : " + this.inventories + "</td></tr>");
jQuery(this.infoTable).append("<tr><td>" + icml + "</td><td> " + this.icml + "</td></tr>");
jQuery(this.infoTable).append("<tr><td>" + history + "</td><td> " + this.history + "</td></tr>");
jQuery(this.infoTable).append("<tr><td>" + inventories + "</td><td> " + this.inventories + "</td></tr>");
}
RetailcrmCronInfo.prototype.clearCronTasks = function () {
let _this = this;
jQuery.ajax({
type: "POST",
url: window.location.origin + '/wp-admin/admin-ajax.php?action=clear_cron_tasks',
success: function (response) {
alert(_this.messageSuccessful);
}
});
};
window.RetailcrmCronInfo = RetailcrmCronInfo;
if (!(typeof RetailcrmCronInfo === 'undefined')) {

View File

@ -62,6 +62,7 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
<?php
}
/**
* Initialize integration settings form fields.
*/
@ -567,6 +568,15 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
'type' => 'heading',
'class' => 'debug_info_options'
];
$this->form_fields['clear_cron_tasks'] = [
'label' => __('Clear', 'retailcrm'),
'title' => __('Clear cron tasks', 'retailcrm'),
'type' => 'button',
'description' => __('If you change the time interval, need to clear the old cron tasks', 'retailcrm'),
'desc_tip' => true,
'id' => 'clear_cron_tasks'
];
}
} elseif (empty($apiUrl) === false && empty($apiKey) === false) {
$api = new WC_Retailcrm_Proxy(

View File

@ -82,6 +82,7 @@ if (!class_exists('WC_Retailcrm_Base')) {
add_action('wp_ajax_content_upload', [$this, 'count_upload_data'], 99);
add_action('wp_ajax_generate_icml', [$this, 'generate_icml']);
add_action('wp_ajax_upload_selected_orders', [$this, 'upload_selected_orders']);
add_action('wp_ajax_clear_cron_tasks', [$this, 'clear_cron_tasks']);
add_action('admin_print_footer_scripts', [$this, 'ajax_generate_icml'], 99);
add_action('woocommerce_update_customer', [$this, 'update_customer'], 10, 1);
add_action('user_register', [$this, 'create_customer'], 10, 2);
@ -122,9 +123,18 @@ if (!class_exists('WC_Retailcrm_Base')) {
*/
public function api_sanitized($settings)
{
$timeInterval = apply_filters(
'retailcrm_cron_schedules',
[
'icml' => 'three_hours',
'history' => 'five_minutes',
'inventories' => 'fiveteen_minutes',
]
);
if (isset($settings['sync']) && $settings['sync'] == static::YES) {
if (!wp_next_scheduled('retailcrm_inventories')) {
wp_schedule_event(time(), 'fiveteen_minutes', 'retailcrm_inventories');
wp_schedule_event(time(), $timeInterval['inventories'], 'retailcrm_inventories');
}
} elseif (isset($settings['sync']) && $settings['sync'] == static::NO) {
wp_clear_scheduled_hook('retailcrm_inventories');
@ -132,7 +142,7 @@ if (!class_exists('WC_Retailcrm_Base')) {
if (isset($settings['history']) && $settings['history'] == static::YES) {
if (!wp_next_scheduled('retailcrm_history')) {
wp_schedule_event(time(), 'five_minutes', 'retailcrm_history');
wp_schedule_event(time(), $timeInterval['history'], 'retailcrm_history');
}
} elseif (isset($settings['history']) && $settings['history'] == static::NO) {
wp_clear_scheduled_hook('retailcrm_history');
@ -140,7 +150,7 @@ if (!class_exists('WC_Retailcrm_Base')) {
if (isset($settings['icml']) && $settings['icml'] == static::YES) {
if (!wp_next_scheduled('retailcrm_icml')) {
wp_schedule_event(time(), 'three_hours', 'retailcrm_icml');
wp_schedule_event(time(), $timeInterval['icml'], 'retailcrm_icml');
}
} elseif (isset($settings['icml']) && $settings['icml'] == static::NO) {
wp_clear_scheduled_hook('retailcrm_icml');
@ -153,6 +163,21 @@ if (!class_exists('WC_Retailcrm_Base')) {
return $settings;
}
/**
* If you change the time interval, need to clear the old cron tasks
*
* @codeCoverageIgnore Check in another tests
*/
public function clear_cron_tasks()
{
wp_clear_scheduled_hook('retailcrm_icml');
wp_clear_scheduled_hook('retailcrm_history');
wp_clear_scheduled_hook('retailcrm_inventories');
//Add new cron tasks
$this->api_sanitized($this->settings);
}
/**
* Generate ICML
*
@ -532,6 +557,7 @@ if (!class_exists('WC_Retailcrm_Base')) {
'tr_td_cron' => __('Cron launches', 'retailcrm'),
'tr_td_icml' => __('Generation ICML', 'retailcrm'),
'tr_td_history' => __('Syncing history', 'retailcrm'),
'tr_successful' => __('Cron tasks cleared', 'retailcrm'),
'tr_td_inventories' => __('Syncing inventories', 'retailcrm'),
];

View File

@ -38,27 +38,28 @@ class WC_Retailcrm_Plugin
{
$this->file = $file;
add_filter('cron_schedules', array($this, 'filter_cron_schedules'), 10, 1);
add_filter('cron_schedules', [$this, 'filter_cron_schedules'], 10, 1);
}
public function filter_cron_schedules($schedules)
{
return array_merge(
$schedules,
array(
'five_minutes' => array(
[
'five_minutes' => [
'interval' => 300, // seconds
'display' => __('Every 5 minutes')
),
'three_hours' => array(
],
'three_hours' => [
'interval' => 10800, // seconds
'display' => __('Every 3 hours')
),
'fiveteen_minutes' => array(
],
'fiveteen_minutes' => [
'interval' => 900, // seconds
'display' => __('Every 15 minutes')
)
)
]
],
apply_filters('retailcrm_add_cron_interval', $schedules)
);
}

Binary file not shown.

Binary file not shown.