cron计划,

tech2022-12-26  65

cron计划,

WordPress Cron is one of the most useful features that you’ll want to learn and understand if, like me, you spend a great deal of time working with WordPress.

如果像我一样,如果您花费大量时间使用WordPress,则WordPress Cron是您将要学习和理解的最有用的功能之一。

Being able to run certain functions on a tight schedule is essential for any CMS and WordPress has a set of functions which help make this process very simple and almost effortless.

对于任何CMS来说,能够按计划严格地运行某些功能都是必不可少的,而WordPress具有一组功能,这些功能可以使此过程非常简单且几乎毫不费力。

In this article I will cover the following WordPress Cron features:

在本文中,我将介绍以下WordPress Cron功能:

How is WordPress Cron different than your normal Cron

WordPress Cron与普通Cron有何不同 Scheduling a recurring event

安排定期活动 Scheduling a single event

安排一个活动 Un-scheduling an event

取消安排活动 Specifying custom Cron intervals

指定自定义Cron间隔

什么是Cron? (What is Cron?)

You are probably familiar with the term ‘Cron’ as it relates to the time-based scheduler in Unix systems and although WordPress’ Cron is different; the main idea behind it is the same.

您可能已经熟悉术语“ Cron”,因为它与Unix系统中基于时间的调度程序有关,尽管WordPress的Cron有所不同。 其背后的主要思想是相同的。

Some examples of how WordPress is using it’s Cron system internally is checking for theme and plugin updates and even checking if there are posts ready to be published.

WordPress如何在内部使用其Cron系统的一些示例正在检查主题和插件更新,甚至检查是否有准备发布的帖子。

WordPress Cron有何不同? (How is WordPress Cron Different?)

If you are familiar with Unix’s Cron, you probably think that WordPress’ Cron is always on the lookout for new tasks and running them as they come. This is far from the truth and I’ll explain why shortly.

如果您熟悉Unix的Cron,您可能会认为WordPress的Cron总是在寻找新任务并在它们出现时运行它们。 这与事实相去甚远,我稍后将解释原因。

WordPress’ Cron runs when a page is loaded, whether it’s a front-end or back-end page. In other words, when a page is loaded on your website, WordPress will check if there are any tasks or events that need to run and execute them. If you are thinking this is not ideal, you are absolutely right.

WordPress的Cron在加载页面时运行,无论是前端页面还是后端页面。 换句话说,当您的网站上加载页面时,WordPress将检查是否有任何任务或事件需要运行和执行。 如果您认为这不理想,那是绝对正确的。

If you happen to have a website that doesn’t get too much traffic and you have a task that needs to be executed at a precise time, WordPress will not know the task is due until someone visits your website. Even if it happens to be a search engine bot crawling your website.

如果您碰巧的网站访问量不多,并且您需要在准确的时间执行任务,那么直到有人访问您的网站,WordPress才会知道任务到期。 即使碰巧是搜索引擎机器人在抓取您的网站。

使用Cron安排活动 (Scheduling Events with Cron)

There are two flavors of Cron events that you can schedule with a few lines of code:

您可以通过几行代码来计划两种Cron事件:

Single events – run only once and never again until it is rescheduled again.

单个事件–仅运行一次,并且永远不会再次运行,直到重新安排时间。 Recurring events – run on a schedule and is set to re-occur indefinitely using a time interval.

重复事件–按计划运行,并设置为使用时间间隔无限期重复发生。

安排定期活动 (Scheduling a Recurring Event)

Scheduling a recurring event requires that you create a custom ‘Action’ which must also be registered with Cron. Once the Cron runs, the function attached to the custom ‘Action’ you created earlier is executed.

要安排重复发生的事件,您需要创建一个自定义“操作”,该操作也必须向Cron注册。 Cron运行后,将执行附加到您先前创建的自定义“动作”的功能。

Let’s take a look at the following example where we are going to be deleting post revisions on a daily basis.

让我们看下面的示例,在该示例中,我们将每天删除后期修订。

First we create our custom ‘Action’ which will have attached to it the function we want to run when the hook is called by Cron.

首先,我们创建自定义的“ Action”,当Cron调用该钩子时,它将附加到我们要运行的函数上。

<?php // delete_post_revisions will be call when the Cron is executed add_action( 'delete_post_revisions', 'delete_all_post_revisions' ); // This function will run once the 'delete_post_revisions' is called function delete_all_post_revisions() { $args = array( 'post_type' => 'post', 'posts_per_page' => -1, // We don't need anything else other than the Post IDs 'fields' => 'ids', 'cache_results' => false, 'no_found_rows' => true ); $posts = new WP_Query( $args ); // Cycle through each Post ID foreach( (array)$posts->posts as $post_id ) { // Check for possible revisions $revisions = wp_get_post_revisions( $post_id, array( 'fields' => 'ids' ) ); // If we got some revisions back from wp_get_post_revisions if( is_array( $revisions ) && count( $revisions ) >= 1 ) { foreach( $revisions as $revision_id ) { // Do a final check on the Revisions if( wp_is_post_revision( $revision_id ) ) { // Delete the actual post revision wp_delete_post_revision( $revision_id); } } } } }

For scheduling the recurring event we make use of the wp_schedule_event( $timestamp, $recurrence, $hook, $args ) function which takes 4 arguments:

为了安排重复发生的事件,我们使用wp_schedule_event( $timestamp, $recurrence, $hook, $args )函数,它wp_schedule_event( $timestamp, $recurrence, $hook, $args ) 4个参数:

$timestamp — (integer) (required) The first time that you want the event to occur. This must be in a UNIX timestamp format. WP cron uses UTC/GMT time, not local time. Use time(), which is always GMT in WordPress. (current_time( ‘timestamp’ ) is local time in WordPress.)

$ timestamp —(整数)(必需)您第一次希望事件发生。 这必须是UNIX时间戳格式。 WP cron使用UTC / GMT时间,而不是本地时间。 使用time(),在WordPress中始终为格林尼治标准时间。 (current_time('timestamp')是WordPress中的本地时间。)

$recurrence — (string) (required) How often the event should reoccur. Valid values are ‘hourly‘, ‘twicedaily‘ and ‘daily‘. We’ll see how to create our own time intervals later.

$ recurrence —(字符串)(必需)事件应多久发生一次。 有效值为“ hourly ”,“ daily twicedaily ”和“ daily ”。 稍后我们将看到如何创建自己的时间间隔。

$hook — (string) (required) The name of an action hook to execute.

$ hook —(字符串)(必需)要执行的动作挂钩的名称。

$args — (array) (optional) Arguments to pass to the hook function(s).

$ args —(数组)(可选)传递给hook函数的参数。

First we make sure the event has not been scheduled before and if it hasn’t, we go ahead and schedule it.

首先,我们确保事件尚未事先安排,如果尚未安排,则继续进行计划。

<?php // Make sure this event hasn't been scheduled if( !wp_next_scheduled( 'delete_post_revisions' ) ) { // Schedule the event wp_schedule_event( time(), 'daily', 'delete_post_revisions' ); }

Note that you can also add tie this snippet of code to an action. If you are a plugin writer, you could set up the scheduled event to run the first time the plugin options page is visited. For a much simpler example, we are going to tie it to WordPress’ init action.

请注意,您还可以将此代码段与操作绑定在一起。 如果您是插件编写者,则可以将计划的事件设置为在首次访问插件选项页面时运行。 对于一个简单得多的示例,我们将其与WordPress的init操作联系在一起。

<?php // Add function to register event to WordPress init add_action( 'init', 'register_daily_revision_delete_event'); // Function which will register the event function register_daily_revision_delete_event() { // Make sure this event hasn't been scheduled if( !wp_next_scheduled( 'delete_post_revisions' ) ) { // Schedule the event wp_schedule_event( time(), 'daily', 'delete_post_revisions' ); } }

Now that you know how to schedule recurring events, let’s take a look at creating a single event which will never run again until it is rescheduled.

现在您知道了如何安排重复发生的事件,下面让我们看一下如何创建一个单独的事件,除非重新安排它,否则它将永远不会再次运行。

安排单个事件 (Scheduling a Single Event)

Just as its name suggests, a single event is one that runs once and then it stops. This single event can still be rescheduled again if needed.

顾名思义,单个事件是运行一次然后停止的事件。 如果需要,仍然可以重新安排该单个事件的时间。

The concept behind it is the same as the recurring events. First you register a custom hook which is called by Cron when it runs on the server. Once Cron calls the hook, its function is executed and that’s basically how you get things done.

其背后的概念与重复发生的事件相同。 首先,您注册一个自定义钩子,当它在服务器上运行时,Cron会调用它。 一旦Cron调用了钩子,它的功能就会被执行,这基本上就是您完成工作的方式。

As an example, we are going to be setting an expiration date for posts. Posts will expire 30 days after being published. We are going to be hooking into the publish_post so that we can schedule our single event as soon as the post is published and count down begins.

例如,我们将为帖子设置过期日期。 帖子将在发布30天后过期。 我们将挂在publish_post以便我们可以在发布该帖子并开始倒计时时安排我们的单个事件。

Setting up the function which will delete the post after 30 days.

设置将在30天后删除帖子的功能。

<?php // delete_post_after_expiration will be called by Cron // We are going to be passing the Post ID so we need to specify that // we'll need 1 argument passed to the function add_action( 'delete_post_after_expiration', 'delete_post_after_expiration', 10, 1 ); // This function will run once the 'delete_post_after_expiration' is called function delete_post_after_expiration( $post_id ) { // Takes care of deleting the specified Post wp_delete_post( $post_id, true ); }

Pretty simple, right? Now we need to schedule the event once the post is actually published. In order to accomplish this task we need to use the wp_schedule_single_event( $timestamp, $hook, $args ) function which takes 3 arguments.

很简单,对吧? 现在,我们需要在帖子实际发布后安排活动。 为了完成此任务,我们需要使用wp_schedule_single_event( $timestamp, $hook, $args )函数,该函数需要3个参数。

$timestamp — (integer) (required) The time you want the event to occur. This must be in a UNIX timestamp format.

$ timestamp —(整数)(必需)您希望事件发生的时间。 这必须是UNIX时间戳格式。

$hook — (string) (required) The name of an action hook to execute.

$ hook —(字符串)(必需)要执行的动作挂钩的名称。

$args — (array) (optional) Arguments to pass to the hook function.

$ args —(数组)(可选)传递给hook函数的参数。

Here is quick look at how all this actions and hooks are put together.

快速浏览一下所有这些动作和挂钩。

<?php // schedule_post_expiration_event runs when a Post is Published add_action( 'publish_post', 'schedule_post_expiration_event' ); function schedule_post_expiration_event( $post_id ) { // Schedule the actual event wp_schedule_single_event( 30 * DAY_IN_SECONDS, 'delete_post_after_expiration', array( $post_id ) ); }

We are using some time constants that WordPress has in place to make our lives easier. For more information on these constants, you can go to “Using Time Constants“, but here is a quick overview:

我们正在使用WordPress提供的一些时间常数来简化我们的生活。 有关这些常量的更多信息,您可以转到“ 使用时间常量 ”,但这是一个快速概述:

MINUTE_IN_SECONDS = 60 (seconds)

MINUTE_IN_SECONDS = 60(秒)

HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDS

HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDS

DAY_IN_SECONDS = 24 * HOUR_IN_SECONDS

DAY_IN_SECONDS = 24 * HOUR_IN_SECONDS

WEEK_IN_SECONDS = 7 * DAY_IN_SECONDS

WEEK_IN_SECONDS = 7 * DAY_IN_SECONDS

YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS

YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS

计划外活动 (Un-scheduling Events)

Now that you know how to schedule recurring and single events, it’s also going to be useful to know how to un-schedule these events.

现在您知道了如何安排重复事件和单个事件,了解如何取消安排这些事件也将很有用。

You might be wondering, why would you want to un-schedule events? There is a good reason, particularly if you include some sort schedule events in your plugins.

您可能想知道,为什么要取消安排活动的时间? 有充分的理由,特别是如果您在插件中包含一些排序时间表事件。

Crons are stored on the wp_options table and by simply deactivating and deleting your plugin. WordPress will still try to run your events even though said plugin is no longer available. Having said that, please make sure you un-schedule events properly within your plugin or custom implementation.

Cron存储在wp_options表中,只需简单地停用和删除插件即可。 即使所说的插件不再可用,WordPress仍将尝试运行事件。 话虽如此,请确保您在插件或自定义实现中正确地取消安排事件的时间。

Un-scheduling Cron events is relatively easy, all you need to know is the name of the hook and when is the next scheduled time that particular Cron is supposed to run. We are going to be using wp_next_scheduled() to find when the next occurrence will take place and only then we can un-schedule it using wp_unschedule_event().

取消计划Cron事件相对容易,您只需要知道钩子的名称以及何时应该运行特定Cron的下一个计划时间即可。 我们将使用wp_next_scheduled()来查找下一次发生的时间,只有那时我们才能使用wp_unschedule_event()取消计划。

Considering our first example, we would un-schedule the event the following way.

考虑我们的第一个示例,我们将通过以下方式取消安排事件的时间。

<?php // Get the timestamp of the next scheduled run $timestamp = wp_next_scheduled( 'delete_post_revisions' ); // Un-schedule the event wp_unschedule_event( $timestamp, 'delete_post_revisions' );

自定义Cron间隔 (Customizing Cron Intervals)

It is possible to set custom Cron intervals which you can use when scheduling events using Cron. To do so, we just need to hook into the cron_schedules filter and add our own. Let’s take a look at adding a custom interval set to run every 10 minutes.

可以设置自定义Cron间隔,您可以在使用Cron安排事件时使用该间隔。 为此,我们只需要挂接到cron_schedules过滤器并添加我们自己的过滤器即可。 让我们看一下添加一个自定义间隔集,该间隔集每10分钟运行一次。

<?php // Add custom cron interval add_filter( 'cron_schedules', 'add_custom_cron_intervals', 10, 1 ); function add_custom_cron_intervals( $schedules ) { // $schedules stores all recurrence schedules within WordPress $schedules['ten_minutes'] = array( 'interval' => 600, // Number of seconds, 600 in 10 minutes 'display' => 'Once Every 10 Minutes' ); // Return our newly added schedule to be merged into the others return (array)$schedules; }

结论 (Conclusion)

Using WordPress’ Cron couldn’t be any easier and it is a very nice and interesting tool which is sure to help you make your plugin more robust. Learning all these functions and putting them into practice with real world applications is the best way to master WordPress’ Cron for scheduling events.

使用WordPress的Cron绝非易事,它是一个非常不错且有趣的工具,可以确保您使插件更强大。 学习所有这些功能并将其与实际应用程序一起使用是掌握WordPress Cron安排事件的最佳方法。

翻译自: https://www.sitepoint.com/mastering-wordpress-cron/

cron计划,

相关资源:wordpress定时任务(wp-cron.php)造成主机CPU比较高的解决办法
最新回复(0)