Add force parameter, timings

This commit is contained in:
Rich Lott / Artful Robot 2024-03-01 11:20:01 +00:00
parent ca1360f8bf
commit 1d28eb4820

View file

@ -17,18 +17,27 @@ use CRM_Core_DAO;
*/ */
class Sync extends \Civi\Api4\Generic\AbstractAction { class Sync extends \Civi\Api4\Generic\AbstractAction {
/**
* Usually this will not act unless the time is right.
*
* @default FALSE
* @var bool
*/
protected $force = FALSE;
public function _run(Result $result) { public function _run(Result $result) {
ini_set('memory_limit', '256M'); ini_set('memory_limit', '256M');
Civi::log()->debug('Begin', ['=start' => 'ContactCatSync', '=timed' => 1]); Civi::log()->debug('Begin', ['=start' => 'ContactCatSync', '=timed' => 1]);
$settings = Civi::settings()->get('contact_categories'); // this does not unserialize $settings = Civi::settings()->get('contact_categories');
$settings = Setting::get(FALSE) $settings = Setting::get(FALSE)
->addSelect('contact_categories') ->addSelect('contact_categories')
->execute()->first()['value'] ?? NULL; ->execute()->first()['value'] ?? NULL;
if (empty($settings['groupIDs'])) { if (empty($settings['groupIDs'])) {
throw new \API_Exception('Unconfigured'); throw new \API_Exception('Unconfigured');
} }
if ($settings['updateAfter'] > time()) { if (!$this->force && time() < $settings['updateAfter']) {
// not needed yet. // not needed yet.
Civi::log()->debug("Skipping because not due until " . date('H:i j M Y', $settings['updateAfter']), ['=' => 'pop']);
return; return;
} }
@ -49,7 +58,7 @@ class Sync extends \Civi\Api4\Generic\AbstractAction {
} }
} }
if ($smartGroups) { if ($smartGroups) {
Civi::log()->debug('Refreshing smart groups', ['=' => 'timed', 'groups' => $smartGroups]); Civi::log()->debug('Refreshing smart groups', ['=' => 'timed,start', 'groups' => $smartGroups]);
\CRM_Contact_BAO_GroupContactCache::loadAll($smartGroups); \CRM_Contact_BAO_GroupContactCache::loadAll($smartGroups);
Civi::log()->debug('', ['=' => 'pop']); Civi::log()->debug('', ['=' => 'pop']);
} }
@ -150,8 +159,16 @@ class Sync extends \Civi\Api4\Generic\AbstractAction {
$summary['changes'] = $n; $summary['changes'] = $n;
$_ = memory_get_peak_usage(TRUE); $_ = memory_get_peak_usage(TRUE);
$summary['memory_use'] = @round($_ / pow(1024, ($i = floor(log($_, 1024)))), 2) . ' ' . ['b', 'kb', 'mb', 'gb', 'tb', 'pb'][$i]; $summary['memory_use'] = @round($_ / pow(1024, ($i = floor(log($_, 1024)))), 2) . ' ' . ['b', 'kb', 'mb', 'gb', 'tb', 'pb'][$i];
Civi::log()->debug('Complete.', ['=' => 'set']);
$result->exchangeArray($summary); $result->exchangeArray($summary);
// Limit to running every 6 hours.
$settings['updateAfter'] = time() + 60 * 60 * 6;
Setting::set(FALSE)
->addValue('contact_categories', $settings)
->execute();
Civi::log()->debug("Complete. Scheduling next run after " . date('H:i j M Y', $settings['updateAfter']), ['=' => 'set']);
} }
} }