在WordPress中怎么设置定时任务?
在WordPress中使用wp-cron插件来设置定时任务
PHP 本身是无法创建定时任务的,但是 WordPress 自带了一个伪定时任务(Cron) API,非常的方便好用,包括 WordPress 本身的定时发布文章都依赖于这个 API
WP Cron 是什么? 是 WordPress 一套定时触发机制, 可以循环安排任务执行. 如: 定时发布新文章, 定期检测版本等功能都是通过这个来实现的.
WP Cron 可以为我们实现什么? 我们可以循环更新和提交网站数据, 节日定期向读者发送贺卡或者表单 ...
它的原理就是将创建的定时任务存储到数据库里,当有人访问的时候就去判断一下是否到时间需要执行这个定时任务,如果到时间则执行。
因为这种原理,所以执行的时间可能会有一些偏差,但随着网站的浏览量攀升和网络爬虫的不断访问,会让定时任务执行的时间越来越准确。
WP-Cron 效率不高, 但还是很方便好用的, 整理了一下相关函数的使用方法如下.
函数
wp_get_schedule
通过勾子别名, 获取预定安排的勾子. 成功时返回循环周期类别 (hourly, twicedaily, daily, ...), 失败时返回 false.
<?php wp_get_schedule( $hook, $args ) ?>
$hook: 勾子别名
$args: 勾子对应函数的参数数组 (可选)
wp_get_schedules
WordPress 默认支持的循环周期类别有 hourly, twicedaily 和 daily. 通过该函数我们可以获取所有这些循环周期数组.
<?php wp_get_schedules() ?>
在默认情况下, 由以上方法获得的数组对象如下.
array( 'hourly' => array( 'interval' => 3600, 'display' => 'Once Hourly' ), 'twicedaily' => array( 'interval' => 43200, 'display' => 'Twice Daily' ), 'daily' => array( 'interval' => 86400, 'display' => 'Once Daily' ) )
我们可以向 cron_schedules 过滤器添加更多的类型. 添加例子如下:
add_filter('cron_schedules', 'cron_add_weekly'); function cron_add_weekly( $schedules ) { // Adds once weekly to the existing schedules. $schedules['weekly'] = array( 'interval' => 604800, // 1周 = 60秒 * 60分钟 * 24小时 * 7天 'display' => __('Once Weekly') ); return $schedules; }
wp_next_scheduled
通过勾子别名, 获取预定安排的下一个运行时刻, 以整型返回. 常用于判断是否已经做了预定安排.
<?php $timestamp = wp_next_scheduled( $hook, $args ); ?>
$hook: 勾子别名
$args: 勾子对应函数的参数数组 (可选)
wp_schedule_event
按周期循环预定安排一个 WordPress 勾子, 在预定时间触发勾子对应的函数.
<?php wp_schedule_event($timestamp, $recurrence, $hook, $args); ?>
$timestamp: 时间 (整型)
$recurrence: 循环周期类别 (hourly, twicedaily, daily, ...)
$hook: 勾子别名
$args: 勾子对应函数的参数数组 (可选)
wp_reschedule_event
按周期循环重新预定安排一个 WordPress 勾子. 但我发现这个方法不能正常使用, Codex 写得很草, 如果哪位清楚知道怎么使用, 请告知一下.
wp_unschedule_event
通过预定时间和勾子别名, 取消预定的安排.
<?php wp_unschedule_event($timestamp, $hook, $args ); ?>
$timestamp: 时间 (整型)
$hook: 勾子别名
$args: 勾子对应函数的参数数组 (可选)
wp_clear_scheduled_hook
通过勾子别名, 移除预定安排的勾子.
<?php wp_clear_scheduled_hook( $hook ); ?>
$hook: 勾子别名
wp_schedule_single_event
预定安排一个 WordPress 勾子, 在预定时间触发勾子对应的函数. 与 wp_schedule_event 不同的是该方法的只安排一次触发, 不存在循环预定.
<?php wp_schedule_single_event($timestamp, $hook); ?>
$timestamp: 时间 (整型)
$args: 勾子对应函数的参数数组 (可选)
从上面的函数可用的参数来看,我们就可以整理出以下几个常用的参数:
参数
$timestamp
(整数)(必须)第一次执行此定时任务的时间,需要传一个时间戳,一般情况下都是当场执行,但不能用 time() 函数,而是用 WordPress 的时间函数 current_time()。
默认值:None
$recurrence
(字符串)(必须)执行频率。每隔多长时间执行一次。可以填写 hourly (每小时执行一次)、twicedaily (每天执行两次,也就是 12 小时执行一次)和 daily (24 小时执行一次)。
默认值:None
$hook
(字符串)(必须)执行的钩子。在执行定时任务的时候会调用这个钩子,往这个钩子挂在函数即可实现定时执行函数。
默认值:None
$args
(数组)(可选)传递的参数,会被传递到挂载到定时钩子的函数里的参数。
默认值:None
返回值
(布尔 | null)如果添加成功则返回 null,不成功则返回 False
例子
if( !wp_next_scheduled( 'test' ) ) wp_schedule_event( current_time( 'timestamp' ), 'twicedaily', 'test' );
首先使用 wp_next_scheduled() 函数判断是否已经创建,如果没创建则创建一个定时任务。
把需要执行的代码挂载到 test 钩子上就行了。
推荐:《WordPress建站教程》

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

Dreamweaver CS6
Visual web development tools
