I'm writing a plugin which collects a pretty large feed. From each feed item a custom post will be created. The feed can also contain images for each item that is uploaded from the remote url. Processing the entire feed can take some time and since I would like to do the processing in the background I am looking into cron as a way to achieve this. Currently I'm doing something like this:
class Cron_Task {
const DEFAULT_TASK_INTERVAL = 30;
public function __construct($taskName, $data) {
add_filter('cron_schedules', array($this, 'addSchedule'));
add_action('cron_task', 'Cron_Task::run');
if (!wp_next_scheduled('cron_task', array($taskName))) {
// Store data in cache.
set_transient($taskName, serialize($data));
wp_schedule_event(time(), $taskName, 'cron_task', array($taskName));
}
}
public static function processItem($data) {
// Execute long running task.
}
public function addSchedule($schedules) {
$schedules['crontask'] = array(
'interval' => self::DEFAULT_TASK_INTERVAL,
'display' => __('Cron_Task'),
);
return $schedules;
}
public static function run($taskName) {
// Get data from cache.
$data = unserialize(get_transient($taskName));
if ($data) {
$item = array_shift($data);
// Process one item.
self::processItem($item);
// Check if we have processed all items.
if (!count($data)) {
delete_transient($taskName);
wp_clear_scheduled_hook('cron_task', array($taskName));
} else {
// Update the items to process.
set_transient($taskName, serialize($data));
}
}
}
}
// When a feed is collected we create a cron_task to be run every 30 seconds.
if (get_feed()) {
$cronTask = new Cron_Task('testEvent', $feed);
}
The above sort of works, but I think there must be a better way of doing this kind of thing? For instance, since the configured cron tasks will only be run on page load, the task might not be run at the desired interval if there are no visitors.
wp-cron.php
at a regular interval then the simplest way would be to just add a new cron job usingcrontab -e
=) This question is like I said more about a good way to implement async tasks, like this project: github.com/techcrunch/wp-async-task