WordPress Cron function is not working

Are you constructing the class properly? Is the file writable? Do you need the interval or can you add the scheduled item if it doesn’t exist.

This example is working, and sets an event 10 seconds into the future.


wp_schedule_event( time() + 10, null, 'ga_order_syn' );


class CronTest {

    function __construct() {
        add_action( 'init', array ( $this, 'g_order_sync' ) );
        add_action( 'ga_order_syn', array ( $this, 'sync_order' ) );
    }

    // init

    public function g_order_sync() {
        if ( ! wp_next_scheduled( 'ga_order_syn' ) ) {
            wp_schedule_event(  time() + 10, null, 'ga_order_syn' );
        }
    }

    // cron job

    public function sync_order() {
        $content = time() . ": some text here";
        $this->_write_content ($content);
    }

    // write content

    private function _write_content( $content="") {
        $path =  $_SERVER[ 'DOCUMENT_ROOT' ] . "/myText.txt";
        if( is_writable($path)) {
            $original = file_get_contents($path);
            $original .= PHP_EOL . $content;
            $fp = fopen( $path, "wb" );
            fwrite( $fp, $original );
            fclose( $fp );
        } else {
            // log error here
        }
    }
}

// must initialize the cron class
$cron_test = new CronTest();