| 1 |
<?php |
| 2 |
/** |
| 3 |
* Auto-sync cron mutual-exclusion guard. |
| 4 |
* |
| 5 |
* Pure function (no WordPress dependency) so it can be unit tested in |
| 6 |
* isolation. The hourly cron and a user's manual import both drive the same |
| 7 |
* mlsimport_item task and write the same progress meta. This decides, from a |
| 8 |
* task's mlsimport_spawn_status, whether the cron may start its own import loop |
| 9 |
* on that task. |
| 10 |
*/ |
| 11 |
|
| 12 |
if ( ! defined( 'ABSPATH' ) ) { |
| 13 |
exit; // Exit if accessed directly |
| 14 |
} |
| 15 |
|
| 16 |
/** |
| 17 |
* Whether the hourly cron may process a task, given its spawn status. |
| 18 |
* |
| 19 |
* The cron runs only on a task that has fully completed a previous import. |
| 20 |
* That single rule excludes both a never-imported task ('') and a task with an |
| 21 |
* import in flight ('started', set by the manual path until its async run ends). |
| 22 |
* |
| 23 |
* @param string $spawn_status The task's mlsimport_spawn_status meta value. |
| 24 |
* @return bool True when the cron may start an import loop on the task. |
| 25 |
*/ |
| 26 |
function mlsimport_cron_should_process_task( string $spawn_status ): bool { |
| 27 |
return 'completed' === $spawn_status; |
| 28 |
} |
| 29 |
|
| 30 |
/** |
| 31 |
* Order the hourly sync's tasks by starvation: oldest last-sync first. |
| 32 |
* |
| 33 |
* GitHub issue #203: processing tasks in the same fixed order every hour let |
| 34 |
* one large early task eat the whole cycle, so the tasks at the bottom were |
| 35 |
* skipped run after run and a region could go 9+ hours without an update. |
| 36 |
* Sorting by the last-sync watermark guarantees the task that has waited the |
| 37 |
* longest is always first in line on the next run. |
| 38 |
* |
| 39 |
* Step by step: |
| 40 |
* 1. Receives every cron-enabled task as id => 'Y-m-d\TH:i' watermark |
| 41 |
* (the task's mlsimport_last_date meta). |
| 42 |
* 2. Sorts ascending by watermark — the fixed-width format compares |
| 43 |
* correctly as a plain string, no date parsing needed. |
| 44 |
* 3. Returns just the task ids, most starved first. |
| 45 |
* |
| 46 |
* @param array<int, string> $tasks Task id => last-sync watermark. |
| 47 |
* @return int[] Task ids, the longest-unsynced task first. |
| 48 |
*/ |
| 49 |
function mlsimport_cron_task_order( array $tasks ): array { |
| 50 |
asort( $tasks, SORT_STRING ); |
| 51 |
return array_keys( $tasks ); |
| 52 |
} |
| 53 |
|