| 1 |
<?php |
| 2 |
class Meow_MWCODE_Modules_Cron { |
| 3 |
|
| 4 |
private $core; |
| 5 |
|
| 6 |
public function __construct( $core ) { |
| 7 |
add_filter( 'cron_schedules', [$this, 'add_cron_schedule'] ); |
| 8 |
add_action( 'init', [$this, 'register_hooks'] ); |
| 9 |
|
| 10 |
$this->core = $core; |
| 11 |
} |
| 12 |
|
| 13 |
public function add_cron_schedule( $schedules ) { |
| 14 |
$schedules['mwcode_once_daily'] = array( |
| 15 |
'interval' => 86400, // 24 hours in seconds |
| 16 |
'display' => esc_html__( 'Code Engine Daily' ), |
| 17 |
); |
| 18 |
return $schedules; |
| 19 |
} |
| 20 |
|
| 21 |
public function register_hooks() { |
| 22 |
|
| 23 |
$snippet = new Meow_MWCODE_Modules_Snippet( $this->core ); |
| 24 |
$snippets = $snippet->get_scheduled(); |
| 25 |
|
| 26 |
foreach ( $snippets as $snippet ) { |
| 27 |
|
| 28 |
$hook = 'mwcode_execute_snippet_' . $snippet['snippetId']; |
| 29 |
|
| 30 |
// Check if the hook exists |
| 31 |
if ( !has_action( $hook ) ) { |
| 32 |
add_action( $hook, function() use ( $snippet ) { |
| 33 |
$this->execute_snippet( $snippet['snippetId'] ); |
| 34 |
}); |
| 35 |
} |
| 36 |
|
| 37 |
// Schedule the event if it's not already scheduled |
| 38 |
if ( !wp_next_scheduled( $hook ) ) { |
| 39 |
|
| 40 |
$targetTime = mktime( $snippet['hours'], $snippet['minutes'] ); |
| 41 |
$this->core->log( '🟢 Scheduling snippet: ' . $snippet['snippetId'] . ' at ' . date( 'H:i:s', $targetTime ) ); |
| 42 |
|
| 43 |
wp_schedule_event( $targetTime, 'mwcode_once_daily', $hook ); |
| 44 |
} else { |
| 45 |
//$this->core->log( '🟠 Snippet already scheduled: ' . $snippet['snippetId'] ); |
| 46 |
} |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
public function execute_snippet( $snippetId ) { |
| 51 |
$this->core->log( '🟢 Executing scheduled snippet: ' . $snippetId ); |
| 52 |
$core = new Meow_MWCODE_Core(); |
| 53 |
$core->run_non_fn_snippet( $snippetId ); |
| 54 |
} |
| 55 |
} |
| 56 |
|