I
I
IvanKalinin2017-02-08 11:21:47
Asynchronous programming
IvanKalinin, 2017-02-08 11:21:47

How to execute a function asynchronously in WP (after sending the template to the user)?

Good time everyone.
Can you tell me how in WP it is possible to execute functions asynchronously without forcing the user to wait for its execution?
In 2 words. From the remote server I receive an array with ~50 objects (it changes periodically) that contain links to images. The images are very large, so when I first receive the array, I want to download images to the server in the background, reduce their size and insert their reduced copy into the template, for faster page loading for the end user.
Tried to do something like this

function cache_images() {
  //скачивание, уменьшение размера изображений 
}

add_action('cache_images', 'cache_images', 10, 1);

function render_template() {
 // получение массива
 // если (еще) нет сохраненных изображений
 // вставляю оригинальные
 // собственно тут и строится шаблон
  wp_schedule_single_event(time(), 'cache_images', $listings); 
}

For some reason wp_schedule_single_event is not executing the cache_images function . Moreover wp_next_scheduled('cache_images') always returns false . I also tried to play with time, for example time() + 3600 . The result is the same. false
If you use register_shutdown_function( 'cache_images', $listings) or do_action('cache_images', $listings); instead Then the user has to wait until all ~ 50 images are uploaded to the server.
Actually, the question is again:
How to give the user a template as is (with original images) and save the images in the background.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Druzhaev, 2017-02-08
@IvanKalinin

By crown. Get it, put it in the cache.
Generally to receive on http and at once to give - not the best idea. Do it through transit caches https://wp-kama.ru/id_6462/wordpress-http-api.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question