我将探索在WorPdress中使用预定事件,称为wp-cron.
下面是一个例子(未经测试,只是作为概念证明写在这里):
// 1.- Register custom escheduled event on plugin activiation
register_activation_hook( __FILE__, \'cyb_plugin_activation\' );
function cyb_plugin_activation() {
if( ! wp_next_scheduled( \'cyb_daily_cron_job\' ) ) {
// Set first run time to today at 12:54 (or tomorrow at that time)
$first_run_time = new DateTime( \'12:54\', new DateTimeZone( get_option( \'timezone_string\' ) ) );
$current_time = new DateTime(\'now\', new DateTimeZone( get_option( \'timezone_string\' ) ) );
if( $current_time->getTimestamp() > $first_run_time->getTimestamp() ){
$first_run_time->modify(\'+1 day\');
}
wp_schedule_event( first_run_time->getTimestamp(), \'daily\', \'cyb_daily_cron_job\' );
}
}
// 2.- Hook a function to our scheduled event
add_action( \'cyb_daily_cron_job\', \'cyb_send_daily_mail\' );
function cyb_send_daily_mail() {
$to = \'[email protected]\';
$subject = \'Post Published by Author\';
$headers = \'From: admin <[email protected]>\' . "\\r\\n";
$message = \'your\';
wp_mail($to, $subject, $message, $headers);
}
// 3.- Remove custom escheduled event on plugin deactiviation
register_deactivation_hook( __FILE__, \'cyb_plugin_deactivation\' );
function cyb_plugin_deactivation() {
wp_clear_scheduled_hook( \'cyb_daily_cron_job\' );
}