WordPress:使用预定事件每晚自动保存文章。

huangapple go评论51阅读模式
英文:

WordPress: Auto save posts every night with scheduled event

问题

I want to save every post at night with a scheduled event.
Because we've a lot of posts, I want to split the posts in chunks of 25.

This is my current code for that:

function autosave_posts() {
    // Set up query arguments
    $args = array(
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => 25,
        'orderby'        => 'ID',
        'order'          => 'ASC',
        'paged'          => 1, // Start with first page
    );

    // Loop through posts until all have been updated
    while ( $posts = new WP_Query( $args ) ) {
        if ( $posts->have_posts() ) {
            while ( $posts->have_posts() ) {
                $posts->the_post();
                wp_update_post( array( 'ID' => get_the_ID() ) );
            }
            wp_reset_postdata();

            // Increment the paged argument to get the next set of posts
            $args['paged']++;
        } else {
            // There are no more posts, so we're done
            break;
        }
    }
}

// Schedule the event if it doesn't already exist
if ( ! wp_next_scheduled( 'autosave_posts' ) ) {
    wp_schedule_event( strtotime( '04:00:00' ), 'daily', 'autosave_posts' );
}

// Hook the function to the scheduled event
add_action( 'autosave_posts', 'autosave_posts' );

I tested it with a time 2 minutes in the future.
But unfortunately the posts were not saved.

I checked the cron events with Cron Crontrol and saw that the event was in the list.
So I runned it.

Some of the posts were saved. But not all of them because the maximum execution time of 60 seconds for the function were exceeded.

I added `sleep(5)` after the `while` loop. But the problem with the maximum execution time is still there.

Now I've two questions:

1. Is the function correct and would run? Was my "time in the future" wrong? I'm not sure which time the function `wp_schedule_event` uses.
2. Is there a way to prevent the problem with the `maximum execution time`? Can I split the function in any way? I thought the 25 post chunks were enough

<details>
<summary>英文:</summary>

I want to save every post at night with a scheduled event.
Because we&#39;ve a lot of posts, I want to split the posts in chunks of 25.

This is my current code for that:

    function autosave_posts() {
    	// Set up query arguments
    	$args = array(
    		&#39;post_type&#39;      =&gt; &#39;post&#39;,
    		&#39;post_status&#39;    =&gt; &#39;publish&#39;,
    		&#39;posts_per_page&#39; =&gt; 25,
    		&#39;orderby&#39;        =&gt; &#39;ID&#39;,
    		&#39;order&#39;          =&gt; &#39;ASC&#39;,
    		&#39;paged&#39;          =&gt; 1, // Start with first page
    	);
    
    	// Loop through posts until all have been updated
    	while ( $posts = new WP_Query( $args ) ) {
    		if ( $posts-&gt;have_posts() ) {
    			while ( $posts-&gt;have_posts() ) {
    				$posts-&gt;the_post();
    				wp_update_post( array( &#39;ID&#39; =&gt; get_the_ID() ) );
    			}
    			wp_reset_postdata();
    
    			// Increment the paged argument to get the next set of posts
    			$args[&#39;paged&#39;]++;
    		} else {
    			// There are no more posts, so we&#39;re done
    			break;
    		}
    	}
    }
    
    // Schedule the event if it doesn&#39;t already exist
    if ( ! wp_next_scheduled( &#39;autosave_posts&#39; ) ) {
    	wp_schedule_event( strtotime( &#39;04:00:00&#39; ), &#39;daily&#39;, &#39;autosave_posts&#39; );
    }
    
    // Hook the function to the scheduled event
    add_action( &#39;autosave_posts&#39;, &#39;autosave_posts&#39; );

I tested it with a time 2 minutes in the future.
But unfortunately the posts were not saved.

I checked the cron events with Cron Crontrol and saw that the event was in the list.
So I runned it.

Some of the posts were saved. But not all of them because the maximum execution time of 60 seconds for the function were exceeded.

I added `sleep(5)` after the `while` loop. But the problem with the maximum execution time is still there.

Now I&#39;ve two questions:

 1. Is the function correct and would run? Was my &quot;time in the future&quot; wrong? I&#39;m not sure which time the function `wp_schedule_event` uses.
 2. Is there a way to prevent the problem with the `maximum execution time`? Can I split the function in any way? I thought the 25 post chunks were enough



</details>


# 答案1
**得分**: 1

尝试在`while`语句后的行上调用[set_time_limit(60)][1]。它将重置每次循环的时间限制,减少超时的机会。

避免使用[sleep()][2]。它没有充分的理由占用稀缺的Web服务器进程。而且,休眠时间不计入时间限制。

但是,一些主机会强加一个总体的、不可重置的时间限制。在这种情况下,您需要将批处理大小从25减小到较小的值。

您没有说明*为什么*要这样做。可能有更有效的方法来完成您需要做的事情。但是没有了解*为什么*的情况下很难提供具体的建议。

[1]: https://www.php.net/manual/en/function.set-time-limit.php
[2]: https://www.php.net/manual/en/function.sleep.php

<details>
<summary>英文:</summary>

Try calling [set_time_limit(60)][1] on the line after your `while` statement. It will reset the time limit to a minute for each time through your loop, reducing the chance of a timeout.

Avoid [sleep()][2]. It ties up a scarce web-server process for no good reason. And, sleeps don&#39;t count against the time limit.

But, some hosts impose an overall, non-resettable time limit. In that case you will need to reduce your batch size from 25 to something smaller.

You didn&#39;t say *why* you do this. There may be a much more efficient way to do what you need to do. But it&#39;s hard to give you specific advice without knowing *why*.


  [1]: https://www.php.net/manual/en/function.set-time-limit.php
  [2]: https://www.php.net/manual/en/function.sleep.php

</details>



huangapple
  • 本文由 发表于 2023年3月31日 16:52:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75896586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定