1

I need a scheduler to automatically update a WordPress website with the new csv after a certain interval.

I found many examples of wp_schedule_event but all were creating cron job on activation of plugin. If i do the same then code executes.But my requirement is to schedule it on submitting a form by admin.

My requirement is:

After plugin activation the admin will select the interval. On submitting this form i want to set the schedular to automatically check for the csv with the interval (selected by admin) so that the site will be updated automatically through new csv.

On form submittion i am calling a php page. On that page, i have written this code:

$interval=$_POST['select_interval'];
        require_once (str_replace ( '//', '/', dirname ( __FILE__ ) . '/' ) . '../../../wp-config.php');
if( !wp_next_scheduled( 'mycronjob' ) ) {
                wp_schedule_event( time(), $interval, 'cronjob',$arguments);
            }
        }
add_action ('cronjob', 'update_csvSchedular');
        function update_csvSchedular($args){
 //code to check for csv
}
  • if you want to do wordpress development do it properly and don't just hack things. Write a plugin to do what you need, force user login to change settings etc. After you gain experience doing things the right way, you will understand enough the pitfalls of trying to invoke wordpress from the outside to consider if the effort of doing such thing is worth your time. – Mark Kaplun Jul 11 '16 at 9:05
1

It's wrong to execute wp_schedule_event in plugin activation and cronjob tag. The correct tag to hook is wp.

WordPress internal cron system works by "request-response" method, it checks for scheduled events immediately after any request to the whole system, after checking the scheduled events, it loads next parts of the system.

So, hooking scheduling to init is too early and cronjob, plugin activation and etc. are too late, they might work, but that's not the right way.

The best way to schedule your event by user-given data, is getting the data from the database, you can save admin given setting in database (for example update_option) and schedule the event by the given value (get_option) hooked to wp tag.

For example:

add_action( 'wp', 'my_scheduled_event' );
function my_scheduled_event() {
  $interval = get_option( 'task_interval' );
    if ( ! wp_next_scheduled( 'my_daily_task' ) )
        wp_schedule_event( time(), $interval, 'my_daily_task' );
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.