WordPress: Cron locking and Queue

I have some CPU intensive scripts that I don't want to run concurrently. Every now and again the scripts will overlap and crash the server. Already at 2GB and the mysql container still crashes.

I have a crontab setup to hit example.com/cron.php?do_cron=randstr every 15 minutes.

Is there any way to place a lock and only execute one cron task at a time? When it's done, the next one would then run.

I know this can be accomplished using PHP's file locking mechanism (but then it doesn't queue the next task). Not sure if WP does this on its own.

All help appreciated!

Topic wp-cron wp-query cron Wordpress

Category Web


Simple Cronjob Walker

  1. Create a CPT cronjob for your cronjobs.
  2. Add the relevant post meta data (action, last_executed,… and whatever you need)
  3. Create a walker function

    function my_cronjob_walker() {
        $args= array(
            'post_type' => 'cronjob',
            'posts_per_page' => 1,
            'meta_key' => 'last_executed'
            'orderby' => 'meta_value',
        );
        $cronjob = new WP_Query($args);
        if ($cronjob->have_posts()) while ($cronjob->have_posts()) {
            $cronjob->the_post();
            // do your cronjob stuff here
            do_action(get_post_meta(get_the_ID(), 'action', true);
            update_post_meta(get_the_ID(), 'last_executed', date('c'));
        }
    }
    if ( ! wp_next_scheduled( 'do_cronjob_walker' ) ) {
        wp_schedule_event( time(), 'hourly', 'do_cronjob_walker' );
    }
    
    add_action( 'do_cronjob_walker', 'my_cronjob_walker' );
    

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.