Home > Enterprise >  doing_action() function stops my code from running
doing_action() function stops my code from running

Time:09-23

My action is called by WP Cron so I'm trying to prevent it from running twice at the same time. So, I have the following function that uses doing_action function to check if the action is running. Apparently, the code below can't run even when the action is not running. But when I removed the doing_action check, the code runs.

function upload_to_ipfs() {

    if ( !doing_action( 'upload_file' ) ) {
        //Code to run here
    }
}
add_action( 'upload_file', 'upload_to_ipfs' );

CodePudding user response:

You should probably have a look at site transients.

<?php

function so_73821350_get_transient_name() {
    return 'so_73821350_transient_name'; // replace this with whatever you want
}

function so_73821350_upload_to_ipfs() {

    // get the existing transient
    //
    // If the transient does not exist, does not have a value, or has expired, 
    // then the return value will be false.
    $process_running = get_site_transient( so_73821350_get_transient_name() );

    if ( ! process_running ) {
        // bail out in case the transient exists and has not expired
        // this means the process is still running
        return; 
    }

    // set the transient to flag the process as started
    // 60 is the time until expiration, in seconds
    set_site_transient( so_73821350_get_transient_name(), 1, 60);

    // Run the upload process here
    
    upload_function();

    // ...
    

    // delete the transient to remove the flag and allow the process to run again
    delete_site_transient( so_73821350_get_transient_name() ); 
    
}
add_action( 'upload_file', 'so_73821350_upload_to_ipfs' );

docs:

get_site_transient()

set_site_transient()

delete_site_transient()

CodePudding user response:

You're running into a scenario where the code won't run because it's calling !doing_action on itself because the action IS running.

Also,

Wordpress doing_action works by looking at a global PHP variable is all.

This will not work since you're probably not on the same thread process (since a new one is started with every PHP request on most servers).

In which case you'll have to resort to an alternative method for checking.

One such alternative is checking the servers running processes for the action. Take a look at something like this https://write.corbpie.com/check-if-a-process-is-running-on-linux-with-php/ to help guide you in the right direction.

function is_server_doing_action(string $process): bool
{
    if (empty(trim(shell_exec("pgrep $process")))) {
        return false;
    } else {
        return true;
    }
}
function upload_to_ipfs() {

    if ( !is_server_doing_action( 'upload_file' ) ) {
        //Code to run here
    }
}
add_action( 'upload_file', 'upload_to_ipfs' );
  • Related