【问题标题】:How to run a function automatically on scheduled Intervals?如何在预定的时间间隔内自动运行功能?
【发布时间】:2020-06-05 13:49:48
【问题描述】:

我正在为一个 Wordpress 网站开发一个插件,我想在每个月的第一天生成一份报告并将其发送给用户/管理员。

在服务器中创建 Cron 作业将是一个完美的解决方案,但以编程方式创建 Cron 作业几乎没有障碍,因为过程因服务器而异(我猜)。 所以我正在考虑一个 WordPress 函数,而不是在执行这项工作的服务器中创建一个 Cron 作业。

如果你们有任何想法,请告诉我。

【问题讨论】:

    标签: wordpress cron wordpress-hook


    【解决方案1】:

    如果间隔时间已经过去,它们只会在加载 WordPress 时运行

    add_filter( 'cron_schedules', 'isa_add_every_three_minutes' );
    function isa_add_every_three_minutes( $schedules ) {
        $schedules['every_three_minutes'] = array(
                'interval'  => 60,
                'display'   => __( 'Every 1 Minutes', 'textdomain' )
        );
        return $schedules;
    }
    
    // Schedule an action if it's not already scheduled
    if ( ! wp_next_scheduled( 'isa_add_every_three_minutes' ) ) {
        wp_schedule_event( time(), 'every_three_minutes', 'isa_add_every_three_minutes' );
    }
    
    // Hook into that action that'll fire every three minutes
    add_action( 'isa_add_every_three_minutes', 'every_three_minutes_event_func' );
    function every_three_minutes_event_func() {
        $content = "some text here";
        $fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/wordpressrootfolder/".time()."-myText.txt","wb");
        fwrite($fp,$content);
        fclose($fp);
    }
    

    【讨论】:

    • 这两个答案都是相似的,而我希望即使未加载网站也能运行该功能。有没有其他方法可以在不使用 Server Cron Jobs 的情况下实现这一目标?
    • wget -q -O - example.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1 cron 任务集在你的服务器中
    • 由于配置 Cron 作业因服务器而异,我想在不使用服务器 Cron 作业的情况下自动化功能。
    【解决方案2】:

    我自己找到了解决方案。我希望它对其他人有帮助。

    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.
    

    【讨论】:

    • 这不是真正的解决方案,这更像是一种解决方法。这只会在加载 WordPress 时运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    相关资源
    最近更新 更多