我有一个只想通过cron作业运行的函数。是否有一种方法可以检查特定的计划事件是否正在调用此函数而不是其他任何函数?
检查函数是否被cron作业调用
3 个回复
最合适的回答,由SO网友:Anh Tran 整理而成
WordPress有一个常量DOING_CRON
这可以帮助我们知道我们是否在做cron的工作。定义见wp-cron.php
文件
因此,您可以在代码中检查此常量:
if ( defined( \'DOING_CRON\' ) )
{
// Do something
}
SO网友:kaiser
看看»Cron API inspector«, 是我写的question #18017. 该插件构建了一个表,该表显示在shutdown
-钩子/页的结尾。
它使用_get_cron_array()
函数检索所有已注册的;计划的操作。另一个有用的功能是wp_get_schedules()
. 第三种方法是调用_get_cron_array()
直接,通过呼叫get_option( \'cron\' );
- 最好使用WP core中的默认API函数。
如果您想知道当前是否在Cron作业中,那么可以检查defined( \'DOING_CRON\' ) AND DOING_CRON
.
SO网友:MonkeyTime
我不是studies development(我只是一个爱好者),但我认为您可以在活动中添加add\\u操作
这只是一份简历。。。
//to the event
if(your_condition)
{
add_action(\'original_event_to_hook\', \'your_scheduled\');
}
function your_scheduled()
{
//create a param here
//And shedule your function with arg
wp_schedule_event(time(), \'hourly\', \'your_function\', array(\'param_1\' => value));
}
function your_function($args){
$verification = $args[\'param_1\'];
if($verification)
{
//OK
//Eventually delete this schedule with this specific arg
}
}
要检索cron“your\\u function”的列表,其中包含以下参数 //Get a filtered list of cron hooks
function kw_filter_crons_hooks($hooks = false, $args = false)
{
$crons = get_option(\'cron\');
if (!$crons)
{
$crons[0] = NULL;
}
$filter = array();
$cronlist = array();
$schedule = array();
foreach($crons as $timestamp => $cron)
{
//@param $hooks = string \'schedule\'
//@param $args = false
//Return an array of cron task sheduled
$schedule[] = $cron;
if(!$schedule && $hooks == \'schedule\' && $args == false)
{
$schedule[0] = NULL;
}
foreach($hooks as $hook)
{
if(isset($cron[$hook]))
{
//@param $hooks = array($hook);
//@param $args = false
//Return an array of cron task sheduled
$cronlist[] = $cron;
if(!$cronlist && is_array($hooks) && $args == false)
{
$cronlist[0] = NULL;
}
if(!empty($args))
{
foreach($cronlist as $key => $value)
{
foreach($value as $k => $v)
{
foreach($v as $x => $y)
{
foreach($args as $arg => $val)
{
if ($y[\'args\'][$arg] == $val)
{
//@param $hooks = array($hook);
//@param $args = array($arg);
//Return an array of cron task specified filtered by arg
$filter[$x] = $y;
if(!$filter && is_array($hooks) && is_array($args))
{
$filter[0] = NULL;
}
}
}
}
}
}
}
}
}
}
if(is_array($hooks) && $args === false && $cronlist)
{
return $cronlist;
}
else if(is_array($hooks) && is_array($args) && $filter)
{
return $filter;
}
else if($hooks === \'schedule\' && $args === false && $schedule)
{
return $schedule;
}
else if($hooks === false && $args === false && $crons)
{
return $crons;
}
else
{
return false;
}
}
//Usage
$cron_filtered = kw_filter_crons_hooks(array(\'your_function\'), array(\'param_1\' => value));
var_dump($cron_filtered);
结束