【问题标题】:WordPress - wp_schedule_event run between two timesWordPress - wp_schedule_event 在两次之间运行
【发布时间】:2026-01-29 18:40:01
【问题描述】:

我正在通过 WP Cron 运行我的自定义脚本。

/**
 * Plugin activation function
 */
function mcsPEventsActivation()
{
    // Schedule cron
    if (! wp_next_scheduled('mcs_populate_cron_hook')) {
        // Log cron job hook
        if (function_exists('mcsWriteLog')) {
            mcsWriteLog('mcs_populate_cron_hook cron job starting now');
        }
        wp_schedule_event(time(), 'ten_minutes', 'mcs_populate_cron_hook');
    }
}
register_activation_hook(__FILE__, 'mcsPEventsActivation');
// Add custom action to execute code.
add_action("mcs_populate_cron_hook", "mcsPopulateScrappedData", 12);

我将“重复”参数设置为自定义计划,即“十分钟”。

我知道我可以通过设置“时间戳”参数在特定时间运行此计划作业,但我希望此计划作业仅在上午 6:00 到上午 8:00 期间运行。

我该怎么做?

【问题讨论】:

    标签: php wordpress plugins cron


    【解决方案1】:

    要完成您的任务,您可以更改您在插件激活挂钩中注册的 cron 计划操作。它仅在插件激活时触发一次。您可以执行以下操作,以您的特定时间间隔检查每个负载并安排 cron 事件 -

    /**
     * Plugin Init function
     */
    function mcsPEventsActivation()
    {
        $now = new DateTime();
        $begin = new DateTime('6:00');
        $end = new DateTime('8:00');
    
        if ($now >= $begin && $now <= $end){
            // Schedule cron
            if (! wp_next_scheduled('mcs_populate_cron_hook')) {
                // Log cron job hook
                if (function_exists('mcsWriteLog')) {
                    mcsWriteLog('mcs_populate_cron_hook cron job starting now');
                }
                wp_schedule_event(time(), 'ten_minutes', 'mcs_populate_cron_hook');
            }
        } else {
            if (wp_next_scheduled('mcs_populate_cron_hook')) {
                $timestamp = wp_next_scheduled( 'mcs_populate_cron_hook' );
                wp_unschedule_event( $timestamp, 'mcs_populate_cron_hook' );
                wp_clear_scheduled_hook( 'mcs_populate_cron_hook' );
            }
        }
    }
    add_action( 'init', 'mcsPEventsActivation', 99 );
    

    【讨论】: