Skip to content

Instantly share code, notes, and snippets.

@anatolykulikov
Created September 3, 2025 19:57
Show Gist options
  • Select an option

  • Save anatolykulikov/54442cbd3fecd09d5f8409227f608ae7 to your computer and use it in GitHub Desktop.

Select an option

Save anatolykulikov/54442cbd3fecd09d5f8409227f608ae7 to your computer and use it in GitHub Desktop.
Alternative WP Cron
<?php
/**
* Pseudocron via a tag file in wp-content/service
* It is triggered on every request (init hook), but it is actually triggered no more than once every 10 minutes.
*/
add_action('init', function () {
$dir = WP_CONTENT_DIR . '/service';
$file = $dir . '/timestamp.lock'
if (!is_dir($dir)) {
// wp_mkdir_p will create the entire hierarchy if necessary
if (!function_exists('wp_mkdir_p') || !wp_mkdir_p($dir)) {
return;
}
}
$should_run = false;
$next_ts = time() + 10 * 60; // current time + 10 minutes
$fp = @fopen($file, 'c+');
if (!$fp) {
return;
}
try {
// ЭWe use exclusive file locking to prevent competitive execution
if (!flock($fp, LOCK_EX)) {
fclose($fp);
return;
}
// We read the current value (if available)
clearstatcache(true, $file);
$size = filesize($file);
$current_ts = 0;
if ($size > 0) {
rewind($fp);
$raw = fread($fp, $size);
if ($raw !== false) {
$current_ts = (int)trim($raw);
}
}
// If the current time exceeds or is equal to the timestamp,
// then we specify the next timestamp and overwrite it to a file,
// as well as allow tasks to be completed.
if ($current_ts === 0 || time() >= $current_ts) {
// Updating timestamp for the next 10 minutes
ftruncate($fp, 0);
rewind($fp);
fwrite($fp, (string)$next_ts);
fflush($fp);
// We allow the launch after the lock is released
$should_run = true;
}
flock($fp, LOCK_UN);
fclose($fp);
} catch (\Throwable $e) {
try {
flock($fp, LOCK_UN);
} catch (\Throwable $e2) {
}
fclose($fp);
return;
}
// We are already completing the task without a file lock (so as not to keep it during execution)
if ($should_run) {
if (function_exists('runBackground')) {
runBackground();
}
}
});
/**
* @param string $prefixText
* @return string
*/
function get_update_time_message(string $prefixText = 'The data will be updated'): string
{
$file_path = WP_CONTENT_DIR . '/service/timestamp.lock';
if (file_exists($file_path)) {
$timestamp = file_get_contents($file_path);
if (is_numeric($timestamp)) {
return sprintf(
'%s %s',
$prefixText,
date('H:i:s d.m.Y', intval($timestamp))
);
}
}
return '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment