Come eseguire una funzione ogni 5 minuti?
-
-
Farestimeglio adesaminare ades.Linux cron o servizi cron diterzeparti se haibisogno di unintervalloe di unaprecisione cosìbrevi,You better look into e.g. Linux cron or 3rd party cron services if you need such a short interval and accuracy,
- 0
- 2015-11-10
- birgire
-
il sito ha untrafficointenso .. quindinon c'èbisogno di considerare l'intervallo ditempo .. certo che verrà attivato ogni 2 o 3minuti ..i clientpreferisconofarlo da `functions.php`site havs heavy traffic.. so no need to consider the time interval.. sure it will be triggered for every 2 or 3 minutes.. clients prefer to do it from `functions.php`
- 0
- 2015-11-10
- Foolish Coder
-
non èpossibile attivare unfilephp senza che qualcosa siain esecuzione sul server con untimer.its not possible to trigger a php file without something running on the server with a timer.
- 0
- 2015-11-10
- Andrew Welch
-
file?stiamoparlando di unafunzionein functions.phpfile? we are talking about a function in functions.php
- 0
- 2015-11-10
- Foolish Coder
-
Pensi che un servizio dimonitoraggiogratuitopotrebbeessereilping che attiva CRON?http://newrelic.com/server-monitoringDo you think a free monitoring service could be the ping that triggers CRON? http://newrelic.com/server-monitoring
- 0
- 2016-01-30
- jgraup
-
7 risposta
- voti
-
- 2016-01-29
Puoi crearenuovi orari dipianificazionetramite cron_schedules:
function my_cron_schedules($schedules){ if(!isset($schedules["5min"])){ $schedules["5min"] = array( 'interval' => 5*60, 'display' => __('Once every 5 minutes')); } if(!isset($schedules["30min"])){ $schedules["30min"] = array( 'interval' => 30*60, 'display' => __('Once every 30 minutes')); } return $schedules; } add_filter('cron_schedules','my_cron_schedules');
Orapuoiprogrammare latuafunzione:
wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);
Perprogrammarlo solo una volta,racchiudiloin unafunzionee controllaprima dieseguirlo:
$args = array(false); function schedule_my_cron(){ wp_schedule_event(time(), '5min', 'my_schedule_hook', $args); } if(!wp_next_scheduled('my_schedule_hook',$args)){ add_action('init', 'schedule_my_cron'); }
Notailparametro $ args! Non specificandoilparametro $ argsin wp_next_scheduled,ma avendo $ argsper wp_schedule_event,verràpianificato unnumero quasiinfinito dello stessoevento (invece di uno solo).
Infine,crea lafunzioneeffettiva che desiderieseguire:
function my_schedule_hook(){ // codes go here }
Penso che siaimportante ricordare che wp-cron controlla lapianificazioneedeseguei lavoripianificatiin scadenza ogni volta che viene caricata unapagina.
Quindi,se hai un sito web abassotraffico che ha solo 1 visitatore all'ora,wp-cron verràeseguito solo quando quel visitatorenaviganeltuo sito (una volta ogni ora). Se hai un sito ad altotraffico con visitatori che richiedono unapagina ogni secondo,wp-cron verrà attivato ogni secondo causando un carico aggiuntivo sul server.
La soluzione è disattivare wp-crone attivarlotramite un vero cronjobnell'intervallo ditempoin cui si ripetepiù velocementeiljob wp-cronpianificato (5min neltuo caso).
Lucas Rolff spiegailproblemae fornisce la soluzionein dettaglio .
In alternativa,potresti utilizzare un serviziogratuito diterzeparti come UptimeRobot perinterrogareiltuo sito (e attivare wp- cron) ogni 5minuti,senon vuoi disattivare wp-crone attivarlotramite un vero cronjob.
You can create new schedule times via cron_schedules:
function my_cron_schedules($schedules){ if(!isset($schedules["5min"])){ $schedules["5min"] = array( 'interval' => 5*60, 'display' => __('Once every 5 minutes')); } if(!isset($schedules["30min"])){ $schedules["30min"] = array( 'interval' => 30*60, 'display' => __('Once every 30 minutes')); } return $schedules; } add_filter('cron_schedules','my_cron_schedules');
Now you can schedule your function:
wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);
To only schedule it once, wrap it in a function and check before running it:
$args = array(false); function schedule_my_cron(){ wp_schedule_event(time(), '5min', 'my_schedule_hook', $args); } if(!wp_next_scheduled('my_schedule_hook',$args)){ add_action('init', 'schedule_my_cron'); }
Note the $args parameter! Not specifying the $args parameter in wp_next_scheduled, but having $args for wp_schedule_event, will cause an almost infinite number of the same event to be scheduled (instead of just one).
Finally, create the actual function that you would like to run:
function my_schedule_hook(){ // codes go here }
I think it is important to mention that wp-cron is checking the schedule and running due scheduled jobs each time a page is loaded.
So, if you have a low traffic website that only has 1 visitor an hour, wp-cron will only run when that visitor browses your site (once an hour). If your have a high traffic site with visitors requesting a page every second, wp-cron will be triggered every second causing extra load on the server.
The solution is to deactivate wp-cron and trigger it via a real cron job in the time interval of you fastest repeating scheduled wp-cron job (5 min in your case).
Lucas Rolff explains the problem and gives the solution in detail.
As an alternative, you could use a free 3rd party service like UptimeRobot to query your site (and trigger wp-cron) every 5 minutes, if you do not want to deactivate wp-cron and trigger it via a real cron job.
-
- 2015-11-10
Seiltuo sito riceve untrafficointenso,potrestiprovare a utilizzare
set_transient()
pereseguirlo (molto approssimativamente) ogni 5minuti,adesempio:function run_every_five_minutes() { // Could probably do with some logic here to stop it running if just after running. // codes go here } if ( ! get_transient( 'every_5_minutes' ) ) { set_transient( 'every_5_minutes', true, 5 * MINUTE_IN_SECONDS ); run_every_five_minutes(); // It's better use a hook to call a function in the plugin/theme //add_action( 'init', 'run_every_five_minutes' ); }
If your site does get heavy traffic then you could try using
set_transient()
to run it (very approximately) every 5 minutes, eg:function run_every_five_minutes() { // Could probably do with some logic here to stop it running if just after running. // codes go here } if ( ! get_transient( 'every_5_minutes' ) ) { set_transient( 'every_5_minutes', true, 5 * MINUTE_IN_SECONDS ); run_every_five_minutes(); // It's better use a hook to call a function in the plugin/theme //add_action( 'init', 'run_every_five_minutes' ); }
-
Bene,ehm,sì?! ...Well, er, yeah?!...
- 0
- 2015-11-10
- bonger
-
sì.,NONfunziona .. ho usatoil seguente codicein `functions.php` quando vieneeffettuata una visita allapagina,verràeffettuato un aggiornamento a unatabellanelmio database .. `funzione run_evry_five_minutes () {$ homepage=file_get_contents ('link da visitare');echo $ homepage;} ".Ma latabella DBnon viene aggiornatanemmeno dopo 6minuti.yeah., it's NOT working.. i've used following code in `functions.php` when a visit make to the page, an update will be made to a table in my database.. `function run_evry_five_minutes() { $homepage = file_get_contents('link to visit'); echo $homepage; }`. But the DB table is not updated after 6 minutes even.
- 0
- 2015-11-10
- Foolish Coder
-
Non soperchénonfunzionaperte,main realtàpensarci solo usando `get_transient ()`/`set_transient ()` senza le cose di cron hamoltopiù senso,moltopiù semplice,aggiornerà la risposta ...Don't know why it's not working for you but actually thinking about it just using `get_transient()`/`set_transient()` without the cron stuff makes a lot more sense, much simpler, will update answer...
- 0
- 2015-11-10
- bonger
-
@bonger è unabuona alternativa a wp_schedule_event ()?@bonger is this good alternative for wp_schedule_event() ?
- 0
- 2016-05-08
- Marko Kunic
-
@ MarkoKunić Non so adessere onesto,non l'hoprovato ... è stato offerto solo come soluzione alternativama se loprovifaccelo sapere ...!(La risposta di Johano Fierra sembrabuona http://wordpress.stackexchange.com/a/216121/57034)@MarkoKunić Don't know to be honest, haven't tried it... it was only offered as a workaround but if you try it out let us know...! (Johano Fierra's answer looks good http://wordpress.stackexchange.com/a/216121/57034 )
- 0
- 2016-05-09
- bonger
-
@bongerfunziona,ma è la stessa cosa,senon sei sul sito web,nonfunzionerà@bonger it is working, but it is the same thing, if you are not on website, it won't run
- 0
- 2016-05-10
- Marko Kunic
-
Ebbene sì,comemenzionatoin varipunti di questapagina,ènecessario un vero cronjob di qualcheforma o altroperfarlo senza richiedere visitatori ... (grazieperilfeedbackperò.)Well yes as mentioned in various places on this page you need a real cron job of some form or other to do it without requiring visitors....(thanks for the feedback though.)
- 0
- 2016-05-11
- bonger
-
- 2018-03-05
Puoi attivarlonell'attivazione delplug-in anzichéin ogni chiamata delplug-in:
//Add a utility function to handle logs more nicely. if ( ! function_exists('write_log')) { function write_log ( $log ) { if ( is_array( $log ) || is_object( $log ) ) { error_log( print_r( $log, true ) ); } else { error_log( $log ); } } } /** * Do not let plugin be accessed directly **/ if ( ! defined( 'ABSPATH' ) ) { write_log( "Plugin should not be accessed directly!" ); exit; // Exit if accessed directly } /** * ----------------------------------------------------------------------------------------------------------- * Do not forget to trigger a system call to wp-cron page at least each 30mn. * Otherwise we cannot be sure that trigger will be called. * ----------------------------------------------------------------------------------------------------------- * Linux command: * crontab -e * 30 * * * * wget http://<url>/wp-cron.php */ /** * Add a custom schedule to wp. * @param $schedules array The existing schedules * * @return mixed The existing + new schedules. */ function woocsp_schedules( $schedules ) { write_log("Creating custom schedule."); if ( ! isset( $schedules["10s"] ) ) { $schedules["10s"] = array( 'interval' => 10, 'display' => __( 'Once every 10 seconds' ) ); } write_log("Custom schedule created."); return $schedules; } //Add cron schedules filter with upper defined schedule. add_filter( 'cron_schedules', 'woocsp_schedules' ); //Custom function to be called on schedule triggered. function scheduleTriggered() { write_log( "Scheduler triggered!" ); } add_action( 'woocsp_cron_delivery', 'scheduleTriggered' ); // Register an activation hook to perform operation only on plugin activation register_activation_hook(__FILE__, 'woocsp_activation'); function woocsp_activation() { write_log("Plugin activating."); //Trigger our method on our custom schedule event. if ( ! wp_get_schedule( 'woocsp_cron_delivery' ) ) { wp_schedule_event( time(), '10s', 'woocsp_cron_delivery' ); } write_log("Plugin activated."); } // Deactivate scheduled events on plugin deactivation. register_deactivation_hook(__FILE__, 'woocsp_deactivation'); function woocsp_deactivation() { write_log("Plugin deactivating."); //Remove our scheduled hook. wp_clear_scheduled_hook('woocsp_cron_delivery'); write_log("Plugin deactivated."); }
You can trigger it in plugin activation instead of on each plugin call:
//Add a utility function to handle logs more nicely. if ( ! function_exists('write_log')) { function write_log ( $log ) { if ( is_array( $log ) || is_object( $log ) ) { error_log( print_r( $log, true ) ); } else { error_log( $log ); } } } /** * Do not let plugin be accessed directly **/ if ( ! defined( 'ABSPATH' ) ) { write_log( "Plugin should not be accessed directly!" ); exit; // Exit if accessed directly } /** * ----------------------------------------------------------------------------------------------------------- * Do not forget to trigger a system call to wp-cron page at least each 30mn. * Otherwise we cannot be sure that trigger will be called. * ----------------------------------------------------------------------------------------------------------- * Linux command: * crontab -e * 30 * * * * wget http://<url>/wp-cron.php */ /** * Add a custom schedule to wp. * @param $schedules array The existing schedules * * @return mixed The existing + new schedules. */ function woocsp_schedules( $schedules ) { write_log("Creating custom schedule."); if ( ! isset( $schedules["10s"] ) ) { $schedules["10s"] = array( 'interval' => 10, 'display' => __( 'Once every 10 seconds' ) ); } write_log("Custom schedule created."); return $schedules; } //Add cron schedules filter with upper defined schedule. add_filter( 'cron_schedules', 'woocsp_schedules' ); //Custom function to be called on schedule triggered. function scheduleTriggered() { write_log( "Scheduler triggered!" ); } add_action( 'woocsp_cron_delivery', 'scheduleTriggered' ); // Register an activation hook to perform operation only on plugin activation register_activation_hook(__FILE__, 'woocsp_activation'); function woocsp_activation() { write_log("Plugin activating."); //Trigger our method on our custom schedule event. if ( ! wp_get_schedule( 'woocsp_cron_delivery' ) ) { wp_schedule_event( time(), '10s', 'woocsp_cron_delivery' ); } write_log("Plugin activated."); } // Deactivate scheduled events on plugin deactivation. register_deactivation_hook(__FILE__, 'woocsp_deactivation'); function woocsp_deactivation() { write_log("Plugin deactivating."); //Remove our scheduled hook. wp_clear_scheduled_hook('woocsp_cron_delivery'); write_log("Plugin deactivated."); }
-
- 2015-11-10
Temo che,oltre ad aspettare che qualcuno visitiiltuo sito cheesegue unafunzione,l'unica altra opzione èimpostare un cronjob sultuo server utilizzando qualcosa delgenere https://stackoverflow.com/questions/878600/how-to-create-cronjob-using-bash o setuavere un'interfacciain stile cpanel sultuo server,a volte c'è unaguiper configurarlo.
I'm afraid that other than waiting for someone to visit your site which runs a function, the only other option is to set up a cron job on your server using something like this https://stackoverflow.com/questions/878600/how-to-create-cronjob-using-bash or if you have a cpanel style interface on your server, sometimes there is a gui for setting this up.
-
sì,.,lo capisco .. hogià alcuni crons creati da cPnael ..ma ora sto cercando dieseguire unafunzione da `functions.php`perché quando lafunzione èin un`plugin` oin `functions.php`nonpossiamo chiedere ai client diimpostare un cron da cpanel da soli ..yeah,., I understand that.. I already have some crons created from cPnael.. but now I am trying to run a function from `functions.php` because when the function is in a `plugin` or in `functions.php` we can not ask clients to set up a cron from cpanel on their own..
- 0
- 2015-11-10
- Foolish Coder
-
- 2016-01-30
Ilplug-in Cronjob Scheduler ti consente dieseguire attivitàfrequentiin modo affidabilee tempestivo senza chenessuno debbafarlovisitailtuo sito,tutto ciò di cui haibisogno è almeno 1 azionee unprogramma Unix Crontab.
Èmoltofacile da usaree moltoflessibile.Crei latuafunzionee definisci un'azione al suointerno.Quindipuoi scegliere latua azione dalmenu delplugine attivarla quando vuoi.
The Cronjob Scheduler plugin allows you to run frequent tasks reliably and timely without anyone having to visit your site, all you need is at least 1 action and a Unix Crontab schedule.
It's very easy to use, and very flexible. You create your own function, and define an action within it. Then you can choose your action from the plugin menu and fire it whenever you want.
-
- 2015-11-10
Ho unapossibile soluzione utilizzando unafunzione dipianificazionee unafunzione ricorsiva WP Ajax.
- Crea unevento dipianificazione di 60minutipereseguire unafunzione
- Questafunzione attiverà unafunzione ricorsiva utilizzando Ajaxtramite
file_get_contents()
- Lafunzione ajax avrà un contatorenel database con unnumerototale di 60 (per ogniminuto all'interno dell'ora).
- Questafunzione ajax controlleràiltuo contatoreper:
Seil contatore è uguale o superiore a 60,azzereràil contatoree attenderàilprossimo cronjob.
Seil contatore èmultiplo di 5 (quindi ogni 5minuti)eseguirà lafunzione desiderata
E,oltre alle condizioni,dormiràper 59 secondi
sleep(59);
(assumendo che latuafunzione sia veloce). Dopo la sospensione,si attiverà automaticamente utilizzando dinuovofile_get_contents()
.Coseimportanti danotare:
- Creare unmodoperinterrompereilprocesso (ades. controllando un valore sul DB)
- Crea unmodoperimpedire dueprocessi contemporaneamente
- Sufile_get_contentsimpostail limite ditempoper l'intestazione a 2 o 3 secondi,altrimentiil serverpotrebbe avere variprocessiin attesa dinulla
- Potresti voler usare
set_time_limit(90);
per cercare diimpedire al server diinterrompere latuafunzioneprima della sospensione
È una soluzione,nonbuona,e potrebbeesserebloccata dal server. Utilizzando un cronesterno èpossibileimpostare una semplicefunzionee il server utilizzerà le risorse su diessa una volta ogni 5minuti. Utilizzando questa soluzione,il server utilizzerà le risorse su diessotuttoiltempo.
I have a possible solution using a schedule function and a recursive WP Ajax function.
- Create a schedule event of 60 minutes to run a function
- This function will trigger a recursive function using Ajax through
file_get_contents()
- The ajax function will have a counter on the database with a total number of 60 (for each minute inside the hour).
- This ajax function will check your counter to:
If counter equal or higher than 60 it will reset counter and await for the next cron job.
If counter multiple of 5 (so at each 5 minutes) it will execute your desired function
And, besides the conditions, it will sleep for 59 seconds
sleep(59);
(assuming your function it's a quick one). After the sleep, it will trigger itself usingfile_get_contents()
again.Important things to note:
- Create a way to interrupt the process (i.e. checking a value on the DB)
- Create a way to prevent 2 processes at same time
- On file_get_contents set the time limit on header to 2 or 3 seconds, otherwise the server may have various processes waiting for nothing
- You may want to use the
set_time_limit(90);
to try prevent server to break your function before the sleep
It's a solution, not a good one, and it may get blocked by the server. Using an external cron you can set a simple function and the server will use resources on it once at each 5 minutes. Using this solution, the server will be using resources on it all the time.
-
- 2017-09-05
La risposta di @johano spiega correttamente comeimpostare unintervallopersonalizzatoperil cronjob di WP. Tuttavia,la seconda domandanon ha risposta,ovvero comeeseguire un cron ogniminuto:
-
Nelfile
wp-config.php
,aggiungiil seguente codice:define('DISABLE_WP_CRON', true);
-
Aggiungi un cronjob (
crontab -e
su unix/linux):1 * * * * wget -q -O - http://example.com/wp-cron.php?doing_wp_cron
Laprimaparte (passaggio 1) disabiliteràil cronjobinterno di WordPress.La secondaparte (passaggio 2)eseguiràmanualmenteil cronjob di WordPress ogniminuto.
Con la risposta di @ Johano (comeeseguire un'attività ogni 5minuti)e lamia (comeeseguiremanualmente cron),dovrestiesserein grado di raggiungereiltuo obiettivo.
@johano's answer correctly explains how to set up a custom interval for WP cron job. The second question isn't answered though, which is how to run a cron every minute:
In the file
wp-config.php
, add the following code:define('DISABLE_WP_CRON', true);
Add a cron job (
crontab -e
on unix/linux):1 * * * * wget -q -O - http://example.com/wp-cron.php?doing_wp_cron
The first part (step 1) will disable WordPress internal cron job. The second part (step 2) will manually run WordPress cron job every minute.
With @Johano's answer (how to run a task every 5 minutes) and mine (how to manually run the cron), you should be able to achieve your goal.
Ho unafunzione daeseguire ogni 5minuti. Hofatto riferimento al codice seguente:
Voglioeseguire questafunzione solo ogni 5minuettiindipendentemente da quandoiniziare. Comepossofarlo?
Inoltre dice cheil codice dice che cron verràeseguito quando un visitatore visitail sito. C'è unmodopereseguireil cron comeperminutie senza aspettare una visita?
diciamo che la seguentefunzione dovrebbeessereeseguita ogni 5minuti,allora comepossofarlo usando
wp_schedule_event()
owp_cron
?