Home > Mobile >  custom scheduled event does not fire
custom scheduled event does not fire

Time:11-25

Hi I have apparently correct snippets here, but I don't see it working. in my case I am needing to delete the views every 10 seconds, but instead of that when updating the page they keep adding views. Does anyone know what is wrong?


add_action('woocommerce_share','setPostViews',70);

function setPostViews() {

  global $product;
    
    $product_id=$product->id;

    $count_key = 'post_views_count';
    $count = get_post_meta($product_id, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($product_id, $count_key);
        add_post_meta($product_id, $count_key, '0');
    }else{
        $count  ;
        update_post_meta($product_id, $count_key, $count);
    }


echo 'view::'.$count;
}


function hits_set_zero_schedule() {
  if ( ! wp_next_scheduled( 'hits_set_to_zero') )
    wp_schedule_event( time(), '10sec', 'hits_set_zero' );
}
add_action( 'wp', 'hits_set_zero_schedule' );

function hits_set_zero_func() {
global $product;
    
    $product_id=$product->id;
  delete_post_meta( $product_id, 'post_views_count', true );
}
add_action( 'hits_set_zero', 'hits_set_zero_func' );





function custom_cron_job_recurrence( $schedules ) 
{
    if(!isset($schedules['10sec']))
    {
        $schedules['10sec'] = array(
            'display' => __( 'Every 10 Seconds', 'twentyfifteen' ),
            'interval' => 10,
        );
    }
     
    if(!isset($schedules['15sec']))
    {
        $schedules['15sec'] = array(
        'display' => __( 'Every 15 Seconds', 'twentyfifteen' ),
        'interval' => 15,
        );
    }
     
    return $schedules;
}
add_filter( ‘cron_schedules’, ‘custom_cron_job_recurrence’ );

El resultado de

echo 'view::'.$count;

it is for example view :: 22, and update view :: 23 and so on, but I expect that every 10 seconds the result returns to 1 (or empty but the function sets 1 as a minimum). Well this does not work on my website.

CodePudding user response:

First, the cron of WordPress does not work as you might be expected as relies on your website to have a request in order to be executed meaning if you don't have a visit within 10 minutes even if a CRON job is scheduled every minute is not going to be executed.

In case you need something more reliable you can always set up a Linux cron job instead which is more reliable.

WP-Cron does not run constantly as the system cron does; it is only triggered on page load.

You can always use wp cli to test your corn being executed as expected with wp cron event run --due-now

Details: https://developer.wordpress.org/cli/commands/cron/event/run/

Reference: https://developer.wordpress.org/plugins/cron/

  • Related