首页 > 解决方案 > 如何在预定的时间间隔内自动运行功能?

问题描述

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

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

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

标签: wordpresscronwordpress-hook

解决方案


如果间隔时间已经过去,它们只会在加载 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);
}

推荐阅读