Skip to content

Instantly share code, notes, and snippets.

@dd32
Last active November 24, 2017 07:16
Show Gist options
  • Save dd32/d1091e4f6316dba126814b5d3ce559bb to your computer and use it in GitHub Desktop.
Save dd32/d1091e4f6316dba126814b5d3ce559bb to your computer and use it in GitHub Desktop.
<?php
/*
* Plugin Name: Cron Example for https://core.trac.wordpress.org/ticket/42660
*/
class Cron_example_42660 {
function __construct() {
add_action( 'admin_menu', array( $this, 'admin_menu' ) );
add_action( 'cron_single_event', array( $this, 'cron_callback' ) );
}
function admin_menu() {
add_menu_page( 'Cron Example', 'Cron Example', 'read', 'cron-example-42660', array( $this, 'render' ) );
add_action( 'admin_init', array( $this, 'maybe_schedule_cron' ) );
add_action( 'admin_init', array( $this, 'maybe_delete_cron_runs' ) );
}
function render() {
echo '<div class="wrap">';
echo '<h1>Cron Example</h1>';
echo '<div>
<form action="admin.php?page=cron-example-42660" method="post"><input type="submit" name="schedule_cron" value="Schedule the cron to run once." /></form>
<form action="admin.php?page=cron-example-42660" method="post"><input type="submit" name="delete_cron_runs" value="Delete the logs" /></form>
</div>';
if ( $runs = (array) get_option( __CLASS__, array() ) ) {
echo '<div>Times the cron has run:<ol>';
foreach ( $runs as $i => $time ) {
echo '<li>' . date_format( DateTime::createFromFormat( 'U.u', $time ), 'Y-m-d H:i:s.u' ) . '</li>';
}
echo '</div>';
} else {
echo "<div>The cron hasn't yet run.</div>";
}
echo '</div>';
}
function maybe_delete_cron_runs() {
if ( isset( $_POST['delete_cron_runs'] ) ) {
delete_option( __CLASS__ );
// Redirect so that if we reload the page, it doesn't re-delete it again.
wp_safe_redirect( 'admin.php?page=cron-example-42660' );
die();
}
}
function maybe_schedule_cron() {
if ( ! isset( $_POST['schedule_cron'] ) ) {
return; // Didn't request the cron run.
}
$when_to_run = time(); // Run now.
if ( wp_next_scheduled( 'cron_single_event' ) ) {
// It's already schedule to run, lets just leave that be.
return;
}
wp_schedule_single_event( $when_to_run, 'cron_single_event' );
// Redirect so that if we reload the page, it doesn't re-schedule it again.
wp_safe_redirect( 'admin.php?page=cron-example-42660' );
die();
}
function cron_callback() {
$option_value = (array) get_option( __CLASS__, array() );
$option_value[] = microtime(1);
update_option( __CLASS__, $option_value );
}
}
new Cron_example_42660();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment