Search code examples
wordpresscronwordpress-hook

How to run a function automatically on scheduled Intervals?


I am developing a plugin for a Wordpress website in which I would like to generate a report on the first day of every month and send it to the users/admin.

Creating a Cron job in the server would be a perfect solution but there are few hurdles in creating Cron Job programmatically as the procedure differs from Server to the server(I guess). So I am thinking of a WordPress function instead of creating a Cron Job in the server that does this job.

Do let me know if you guys have any idea about it.


Solution

  • I found the solution myself. I hope it would be helpful for others.

    function do_this_in_an_hour() {
    
     $postid = "1"; //Supply post-Id here $post->ID.
        wp_update_post(array(
            'ID'    =>  $postid,
            'post_status'   =>  'draft'
            ));     
    }
    add_action( 'my_new_event','do_this_in_an_hour' );
    
    wp_schedule_single_event( time() + 7200, 'my_new_event' );
    
    // time() + 7200 = two hour from now.