我有一个WordPress插件,我想使用cron作业每隔60分钟检查一次外部URL(JSON)是否有任何变化。我想将该响应存储在一个全局变量中,以后可以使用。
到目前为止,这是我的代码......
class GetPosts
{
public $CheckPostDate;
public $SetPostData;
/**
* @param mixed $CheckPostDate
*/
public function setCheckPostDate($CheckPostDate)
{
$this->CheckPostDate = $CheckPostDate;
}
/**
* @param mixed $SetPostData
*/
public function setSetPostData($SetPostData)
{
$this->SetPostData = $SetPostData;
}
public function __construct()
{
// add custom interval
function cron_add_minute( $schedules ) {
// Adds once every minute to the existing schedules.
$schedules['everyminute'] = array(
'interval' => 60,
'display' => __( 'Once Every Minute' )
);
return $schedules;
}
add_filter( 'cron_schedules', 'cron_add_minute' );
// create a scheduled event (if it does not exist already)
function cronstarter_activation() {
if( !wp_next_scheduled( 'mycronjob' ) ) {
wp_schedule_event( time(), 'everyminute', 'mycronjob' );
}
}
// and make sure it's called whenever WordPress loads
add_action('wp', 'cronstarter_activation');
// unschedule event upon plugin deactivation
function cronstarter_deactivate() {
// find out when the last event was scheduled
$timestamp = wp_next_scheduled ('mycronjob');
// unschedule previous event if any
wp_unschedule_event ($timestamp, 'mycronjob');
}
register_deactivation_hook (__FILE__, 'cronstarter_deactivate');
function mycronjob() {
// Get the posts update JSON
$update_args = array(
'timeout' => 30
);
$check_posts_update = wp_remote_get('http://example.com', $update_args);
$checkPostDate = wp_remote_retrieve_body($check_posts_update);
if(empty($checkPostDate)) return false;
$this->setCheckPostDate($checkPostDate);
}
add_action ('mycronjob', [$this, 'my_repeat_function']);
}
}
global $GetPosts;
$GetPosts = new GetPosts();
函数checkRandom()每60秒工作一次,但它不会更新全局变量。
答案 0 :(得分:0)
由于每个请求都是独立的,我要说,将其保存到文件
$data = ['apples','bananas'];
file_put_contents(__DIR__.'/cron.json', json_encode($data));
稍后使用它:
$data = json_decode(file_get_contents(__DIR__.'/cron.json'),true);
if($data !== false) {
}